23
15

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.

GAS(Google Apps Script)でCloud Firestoreを利用する時のメモ

Posted at

Google Apps Script で Cloud Firestore を利用する方法をメモ。

参考URL

Firestore for Google Apps Scripts - Github
【書籍管理シリーズ】GASとFireBase(Firestore)を連携させるよ! - Qiita

事前準備

Firebaseでプロジェクトは作成済み。
Cloud Firestore でデータベースの作成済み。(サンプル)
image.png

Google Apps Script で FirestoreApp のライブラリを追加

1.Google スプレッドシートで「ツール」->「スクリプトエディタ」を開く
2.「リソース」->「ライブラリ」
3."Add a library" に「1VUSl4b1r1eoNcRWotZM3e87ygkxvXltOgyDZhixqncz9lQ3MjfT1iKFw」を入力
4.FirestoreAppを追加(バージョンは最新にしておく。)
image.png

サービスアカウントの作成

1.Google Service Accounts page にアクセス。
2.Firebaseのプロジェクトを選択 ->「サービスアカウントを作成」
image.png
3.サービスアカウント名、サービスアカウントIDを入力 -> 作成
4.ロール -> 「Cloud Datastore オーナー」を選択 -> 続行
5.ユーザーロール、管理者ロールは特に設定しなくてもOK -> 完了
image.png
6.作成したサービスアカウントから「鍵を作成」-> キーのタイプは"JSON"にしてローカルに保存しとく。
image.png

※JSONの中身(サンプル)
image.png

Google Apps Script のコード

読み込み(取得):コレクション内の全てのドキュメント取得

「鍵の作成」で出力したJSON内の "project_id"、"private_key"、"client_email" を使う。function firestoreDataで鍵の情報をセット。

.gs
// CloudFirestoreで認証する為のJSON情報を指定
function firestoreDate() {
  var dateArray = {
    'email': 'test-9999@projecttest99999.iam.gserviceaccount.com',
    'key': '-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n',
    'projectId': 'projecttest-99999'
  }
  return dateArray;
}

// メイン処理部
function myFunction(){
  // CloudFirestoreの認証
  var dateArray = firestoreDate();
  var firestore = FirestoreApp.getFirestore(dateArray.email, dateArray.key, dateArray.projectId);
  // CloudFirestoreからデータを読み込む
  const doc = firestore.getDocument("TEST/voKMytSenYR9ZWYoCeWr");
  console.log(doc);
}
console
[20-12-06 21:58:08:439 JST] { name: 'projects/projecttest-99999/databases/(default)/documents/TEST/voKMytSenYR9ZWYoCeWr',
  fields: 
   { TEST02: { stringValue: '0002' },
     TEST01: { stringValue: '0001' } },
  createTime: '2020-12-06T11:53:16.582462Z',
  updateTime: '2020-12-06T11:53:16.582462Z' }

読み込み(取得):他のプロパティ項目

.gs
function myFunction(){
  // CloudFirestoreの認証
  var dateArray = firestoreDate();
  var firestore = FirestoreApp.getFirestore(dateArray.email, dateArray.key, dateArray.projectId);
  // CloudFirestoreからデータを読み込む
  const doc = firestore.getDocument("TEST/voKMytSenYR9ZWYoCeWr");
  console.log(`フィールドTEST01:${doc.obj.TEST01}`);
  console.log(`フィールドTEST02:${doc.obj.TEST02}`);
  console.log(`データベースの読み込み時間:${doc.read}`);
  console.log(`データベースの更新時間:${doc.updated}`);
  console.log(`データベースの作成時間:${doc.created}`);
  console.log(`Fullドキュメントパス:${doc.name}`);
  console.log(`Localドキュメントパス:${doc.path}`);
}
console
 フィールドTEST01:0001
 フィールドTEST02:0002
 データベースの読み込み時間:Sun Dec 06 2020 22:18:01 GMT+0900 (日本標準時)
 データベースの更新時間:Sun Dec 06 2020 20:53:16 GMT+0900 (日本標準時)
 データベースの作成時間:Sun Dec 06 2020 20:53:16 GMT+0900 (日本標準時)
 Fullドキュメントパス:projects/projecttest-99999/databases/(default)/documents/TEST/voKMytSenYR9ZWYoCeWr
 Localドキュメントパス:TEST/voKMytSenYR9ZWYoCeWr

書き込み(更新):ドキュメント内の上書き更新

「鍵の作成」で出力したJSON内の "project_id"、"private_key"、"client_email" を使う。function firestoreDataで鍵の情報をセット。

.gs
// CloudFirestoreで認証する為のJSON情報を指定
function firestoreDate() {
  var dateArray = {
    'email': 'test-9999@projecttest99999.iam.gserviceaccount.com',
    'key': '-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n',
    'projectId': 'projecttest-99999'
  }
  return dateArray;
}

// メイン処理部
function myFunction(){
  // CloudFirestoreの認証
  var dateArray = firestoreDate();
  var firestore = FirestoreApp.getFirestore(dateArray.email, dateArray.key, dateArray.projectId);
  // 更新するデータ
  const data = {
    "test01": "test001",
    "test02": "test002"
  }
  // CloudFirestoreをドキュメント更新
  firestore.updateDocument("TEST/voKMytSenYR9ZWYoCeWr", data);
}

image.png

書き込み(更新):ドキュメント内の特定フィールド更新

.gs
function myFunction(){
  // CloudFirestoreの認証
  var dateArray = firestoreDate();
  var firestore = FirestoreApp.getFirestore(dateArray.email, dateArray.key, dateArray.projectId);  
  // 追加するデータ
  const data = {
    "test01": "test111"
  }
  // CloudFirestoreをフィールド更新
  firestore.updateDocument("TEST/voKMytSenYR9ZWYoCeWr", data, true);
}

image.png

ドキュメント追加

.gs
function myFunction(){
  // CloudFirestoreの認証
  var dateArray = firestoreDate();
  var firestore = FirestoreApp.getFirestore(dateArray.email, dateArray.key, dateArray.projectId);
  // 追加するデータ
  const data = {
    "test03": "test003",
    "test04": "test004"
  }
  // CloudFirestoreをドキュメント追加
  firestore.createDocument("TEST", data);
}

image.png

23
15
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
23
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?