LoginSignup
37
37

More than 3 years have passed since last update.

GAS:SpreadSheetに登録したデータをFirestoreに送信する

Last updated at Posted at 2019-01-23

Goolgle SpreadSheetに登録したデータをFirestoreに送信するGASを実装してみました。
その記録です。
英語ですが詳しいことは、grahamearley/FirestoreGoogleAppsScriptに書かれています。

日本語で自分が参考にした記事は、【書籍管理シリーズ】GASとFireBase(Firestore)を連携させるよ!です。
どちらもわかりやすく丁寧に書かれていて、思っていたよりもかなり簡単に実装できました。

SpreadSheetのGASでの扱い方については、今回は触れません。
そちらについてはウェブサイト【初心者向けGAS】スプレッドシートのシートを取得する2つの方法がとても参考になるので、読んでみてください。

Firestoreのライブラリを追加

まずは、
ツールからスクリプトエディタを起動し、
リソース>ライブラリ>ライブラリを追加から、

1VUSl4b1r1eoNcRWotZM3e87ygkxvXltOgyDZhixqncz9lQ3MjfT1iKFw

を入力し、その最新のバージョンを選択して保存します(※2019年1月現在では22)。
識別子はFirestoreになっているかと思います。

Firestoreへの認証情報を入力

続いて、GASのファイルに、認証に必要な情報をまとめます。
emailの部分は、設定>サービスアカウントのところに書かれていて、~@sexualhealthmedia-736f9.iam.gserviceaccount.comというアドレスです。
秘密keyはそのページから秘密キーを生成するを押すと作られるjsonファイルの、 "private_key": "
~"、この~~~の部分です。

// Firestoreへ認証する為のデータ情報を設定
function firestoreCertification() {
  var certification = {
    "email": "<Your Project's Service Account>", 
    "key": "-----BEGIN PRIVATE KEY-----\n<Your Secret Key>\n-----END PRIVATE KEY-----\n",
    "projectId": "<Your Project's ID>"
  }
  return certification;
}

Firestoreへ送信するコードを書く

まずは全体のコードを。

//Firestoreへ送信するためのコード
function setDataToFirestore(){
  var sheet = SpreadsheetApp.getActive().getSheetByName('<シート名>');

  //Firestoreへの認証のための変数を用意
  var certification = firestoreCertification();
  var firestore = FirestoreApp.getFirestore(certification.email, certification.key, certification.projectId);

  try {
    //name
    var nameValue = sheet1.getRange('<範囲>').getValue();

    //genre
    var genreValue = sheet1.getRange('<範囲>').getValue();

    var newData = {
          name:nameValue,
          genre:genreValue,
    }

    firestore.updateDocument("<collection名>/<document名>", newData);

  } catch(e) {
    Logger.log(e)
  }

}

Realtime Databaseへ送信するときは、pathは/(スラッシュ)で区切ればよいというシンプルな形式でしたが、
Firestoreの場合、collectionとdocumentという新しい概念によって若干pathの書き方に注意しないといけないっぽいです。

上の例だと、

firestore.updateDocument("<collection名>/<document名>", newData);

のようにpathを設定していますが、仮に

firestore.updateDocument("<collection名>/<document名>/<ほにゃらら>", newData);

というpathを設定した場合、"ほにゃらら"というcollectionが生成されることになります。
では、documentの下に辞書型でデータを保存するためにはどうすればよいかというと、

var newData = {
  name:nameValue,
  genre:genreValue,
}

この例のように、辞書型で値を定義した変数を、updateDocumentの引数として渡せばいいようです。

updateDocument()かcreateDocument()か

Firebaseにデータを追加するメソッドには、updateDocument()とcreateDocument()があるのですが、updateDocumentの方が使いやすそうです。

grahamearley/FirestoreGoogleAppsScriptには、
Note: Although you can call updateDocument without using createDocument to create the document, any documents in your path will not be created and thus you can only access the document by using the path explicitly.

と書かれていて、updateDocumentでもdocumentは作れるけれど、ちゃんとpathは明記してね、とのこと。
つまり、creatDocument()を使えば、特にdocument名(上でいう/<document名>の部分)を書かなくても、勝手にdocumentを生成してくれるけれど、
updateDocument()を使うなら、必ず<collection名>/<document名>まで書きなさいねってことみたいです。

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