GASを使って、SpreadSheet(スプレッドシート)に登録したデータをFirestoreに送信する

firebase

Goolgle SpreadSheetに登録したデータをFirestoreに送信するGASを実装してみました。

こちら(公式のgithub)を参考に実装しました。

手順として記載されているの下記です。

  1. Open the Google Service Accounts page by clicking here.
  2. Select your Firestore project, and then click “Create Service Account.”
  3. For your service account’s role, choose Datastore > Cloud Datastore Owner.
  4. Check the “Furnish a new private key” box and select JSON as your key type.
  5. When you press “Create,” your browser will download a .json file with your private key (private_key), service account email (client_email), and project ID (project_id). Copy these values into your Google Apps Script — you’ll need them to authenticate with Firestore.

firestore の設定などについては、詳述しませんので、ご了承ください。

1、firestore を作成する

webで使用を選択して、firestore database を作成する。

サービスアカウントの設定をする。

歯車 > プロジェクトの設定 > サービスアカウント > 新しい秘密鍵の生成

2、サービスアカウントを作成する

サービスアカウントのページへ行き、プロジェクトが追加されていることを確認して、該当プロジェクトをクリックしてサービスアカウントを作成する。

①の必要事項を入力する。

②はDatastore > Cloud Datastoreオーナーを選択して「完了」。

左メニューの「サービスアカウント」をクリックすると先程作成したサービスアカウントが追加されているので、秘密キーを発行する。

メールアドレス をクリックすると詳細画面へ遷移する。

「キー」をクリックして「鍵を追加」タブでjsonを選択して、鍵をダウンロードする。

GASへコードを書いていく

テストとして、ドキュメントを追加してみる。

先程ダウンロードした json に必要なものは入っているので、mail key projectIdをコピペしていく。

const email = 'projectname-12345@appspot.gserviceaccount.com';
const key = '-----BEGIN PRIVATE KEY-----\nPrivateKeyLine1\nPrivateKeyLine2\nPrivateKeyLineN\n-----END PRIVATE KEY-----';
const projectId = 'projectname-12345'
const firestore = FirestoreApp.getFirestore(email, key, projectId);

const data = {
    "name": "test!"
  }
  firestore.createDocument("FirstCollection", data);

firestore を確認してデータが入っていればOK!

タイトルとURLをコピーしました