createRepoが実行できた。

ブツ

インストール&実行

NAME='Electron.electron-fetch.20220824144925'
git clone https://github.com/ytyaru/$NAME
cd $NAME
npm install
npm start

準備

  1. npm startでアプリ起動し終了する(db/setting.jsonファイルが自動作成される)
  2. db/setting.jsonに以下をセットしファイル保存する
    1. usernameに任意のGitHubユーザ名
    2. tokenrepoスコープ権限を持ったトークン
    3. repoに任意リポジトリ名(mytestrepo等)
  3. dst/mytestrepo/.gitが存在しないことを確認する(あればdstごと削除する)
  4. GitHub上に同名リモートリポジトリが存在しないことを確認する(あれば削除する)

実行

  1. npm startで起動またはアプリでCtrl+Shift+Rキーを押す(リロードする)
  2. git initコマンドが実行される
    • repo/リポジトリ名ディレクトリが作成され、その配下に.gitディレクトリが作成される
  3. 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型になり、それはシリアライズできない型なのだろう。なんて面倒くさいんだ……。これ絶対に忘れてハマるだろうな。