6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【覚書】Gist を簡易的な DB として使う

Last updated at Posted at 2021-05-09

個人的な利用の範囲で、めちゃくちゃ楽な方法でクラウドにデータを保管したいと思ったので、Gist を使ってみた。

GitHub 側の設定

  1. https://github.com/settings/tokens でアクセストークンを取得して控えておく。
  2. https://gist.github.com/ で db.json を作成して URL を控えておく。

JS 側の実装

/**
 * Gist の db.json の内容を取得
 * @param {string} id Gist ID /Example: https://gist.github.com/username/{HERE}
 * @returns {Promise<object>} 内容
 */
const getGist = async (id) =>
  (await (await fetch("https://api.github.com/gists/" + id)).json()).files[
    "db.json"
  ].content;

/**
 * Gist の db.json を書き換え
 * @param {string} id Gist ID /Example: https://gist.github.com/username/{HERE}
 * @param {string} token アクセストークン
 * @param {object} body 書き換える内容
 * @returns {Promise<object>} レスポンス
 */
const setGist = async (id, token, body) =>
  await (
    await fetch("https://api.github.com/gists/" + id, {
      method: "PATCH",
      headers: {
        Accept: "application/vnd.github.v3+json",
        Authorization: "token " + token,
      },
      body: JSON.stringify({
        description: "Updated at " + new Date().toLocaleString(),
        files: {
          "db.json": {
            content: JSON.stringify(body),
          },
        },
      }),
    })
  ).json();

これで OK 。

注意

アクセストークンが漏洩すると色々とヤバいので、見えるところに置くのはガチでやめたほうがいい。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?