以下の内容はhttps://uga-box.hatenablog.com/entry/2022/02/02/000000より取得しました。


【Cloud Functions】外部APIで取得したデータをGCSに定期的に保存する

定期的に外部のAPIをたたいてGCSにjson形式で保存したい

GCPを使っているので

  • Cloud Scheduler
  • Cloud Pub/Sub
  • Cloud Functions

で構成する

f:id:uggds:20220211231058p:plain

functionsの準備

functionsのランタイムはNode.jsが得意なのでNode.jsで作る

必要な依存ライブラリはこんな感じになった

    "@google-cloud/secret-manager": "3.10.1",
    "@google-cloud/storage": "5.18.1",
    "isomorphic-fetch": "3.0.0

secret-managerはAPIトークンの置き場所として使う

GCSにjsonアップロードする実装

GCSにアクセスできるサービスアカウントを作って、そのサービスアカウントで実行するのでjson鍵ファイルは特に不要

こんな感じで実装した

const storage = new Storage(); // projectIdやjson鍵ファイルは不要
const secretManager = new SecretManagerServiceClient();

const bucket = storage.bucket("バケット名");
const file = bucket.file("ファイル名");
await file.save(JSON.stringify(data));

await file.setMetadata({
  contentType: 'application/json',
});

これをGithubにあげて、GCPのCloud Source Repositoriesに登録しておく

トリガーとスケジューラーの作成

あとは、Functionsの実行トリガーをCloud Pub/Subにしてトピックを新規作成 f:id:uggds:20220212000452p:plain:w500

Cloud Pub/Subのトピックを作成したらCloud Schedulerの方の設定でそのトピックを実行するようにして完了

f:id:uggds:20220212001105p:plain:w500




以上の内容はhttps://uga-box.hatenablog.com/entry/2022/02/02/000000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14