LoginSignup
0
0

Cloud Functionsでfirestoreからspreadsheetへデータ書き込み定時実行の手順

Last updated at Posted at 2023-02-02

Cloud Functionsでfirestoreからspreadsheetへデータ書き込み定時実行の手順

Cloud Functionsを定時実行し、firestoreからデータを取得 |> spreadsheetへ書き込む方法のメモを自分用に残しておきます。
サービスアカウントとOAuth2つ認証を使う点が少し混乱しました。

サービスアカウント作成

  1. IAMと管理 > サービスアカウント > サービスアカウントの作成
  2. 権限(IAMロール)の付与
    1. IAMと管理 > IAM > アクセス権を付与

Spreadsheetへの書き込み

  1. ソースコード記述

  2. credentials.json(OAuth2.0クライアントID)の発行
    - https://developers.google.com/sheets/api/quickstart/nodejs

  3. Node.js上で実行しブラウザで認証手続きを行ってcredentials.jsonからtoken.jsonを取得

    • google apis 権限のあるアカウント?で認証する
    • ./functions/token.json へ配置
    • これがないとCloud Functions上で認証できずにtime outする
  4. APIの有効化

    1. Google Spreadsheet APIを有効化

firestoreから取得

  1. serviceAccountKey.json取得

  2. ソースコード記述

デプロイ

$ firebase deploy --only functions

Cloud Schedulerの作成

エラー

GaxiosError: invalid_grant

https://oeconomicus.jp/2021/06/google-api-error/
OAuthの期限切れ(テスト環境では7日で切れる)
再発行する.
token.jsonは消しておくこと.

まとめ

OAuthを使う必要がなければサービスアカウントの認証のみでfirestore、spreadsheetどちらもアクセスできそうだしそれでよさそう。

0
0
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
0
0