createRepoが実行できた。
ブツ
インストール&実行
NAME='Electron.electron-fetch.20220824144925'
git clone https://github.com/ytyaru/$NAME
cd $NAME
npm install
npm start
準備
npm start
でアプリ起動し終了する(db/setting.json
ファイルが自動作成される)db/setting.json
に以下をセットしファイル保存するusername
に任意のGitHubユーザ名token
にrepo
スコープ権限を持ったトークンrepo
に任意リポジトリ名(mytestrepo
等)
dst/mytestrepo/.git
が存在しないことを確認する(あればdst
ごと削除する)- GitHub上に同名リモートリポジトリが存在しないことを確認する(あれば削除する)
実行
npm start
で起動またはアプリでCtrl+Shift+Rキーを押す(リロードする)git init
コマンドが実行されるrepo/リポジトリ名
ディレクトリが作成され、その配下に.git
ディレクトリが作成される
- createRepo実行後、端末に以下のような成功メッセージが表示される
ドキュメント
ググったらelectron-fetchというパッケージを偶然みつけた。よりElectronにふさわしそうな名前だったので試してみた。
また、ブラウザ側のfetch APIと同じ引数、戻り値になるっぽいので、コピペなどしやすいかと思いました。ほかによいパッケージが見つかるまではelectron-fetchを使うことになりそう。
コード抜粋
main.js
const fetch = require('electron-fetch').default;
ipcMain.handle('fetch', async(event, url, options)=>{
const res = await fetch(url, options).catch(e=>console.error(e));
console.log(res)
const json = await res.json()
console.log(json)
return json
//return res
})
ここでres
を返すとAn object could not be cloned.
エラーになってしまう。コードにあるとおりres
にはjson()
メソッドが含まれており、シリアライズできないからだと思われる。なのでjson()
の結果だけを返すようにすると成功する。
preload.js
const {remote,contextBridge,ipcRenderer} = require('electron');
contextBridge.exposeInMainWorld('myApi', {
fetch:async(url, options)=>await ipcRenderer.invoke('fetch', url, options),
})
renderer.js
window.addEventListener('DOMContentLoaded', async(event) => {
const setting = await Setting.load()
const git = new Git(setting?.github)
const hub = new GitHub(setting?.github)
if (setting?.github?.repo) {
const exists = await git.init(document.getElementById('github-repo').value)
if (!exists) {
const res = await window.myApi.fetch(
`https://api.github.com/user/repos`,
{
'method': 'POST',
'headers': {
'Authorization': `token ${setting.github.token}`,
'User-Agent': `${setting.github.username}`,
'Content-Type': 'application/json',
},
'body': JSON.stringify({
'name': `${setting.github.repo}`,
'description': 'リポジトリの説明',
}),
},
)
console.log(res)
}
}
})
ちゃんとres
でGitHub APIの戻り値であるJSONが取得できた! アプリの開発者ツールのコンソールに表示される。
地味な罠として、fetch
に渡すオブジェクトのキーは文字列型にすべくクォートで囲まないとAn object could not be cloned.
エラーになってしまう。おそらくクォートで囲まないとSymbol型になり、それはシリアライズできない型なのだろう。なんて面倒くさいんだ……。これ絶対に忘れてハマるだろうな。