Open2

初めのCloudFirestore体験記(Web)

portgroundportground

Node.jsとCloudFirestoreを組み合わせたアプリを作るための第一歩。クイックスタート: サーバー クライアント ライブラリの使用  |  Firestore  |  Google Cloudを元にfirestoreを体験する。

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

Node.js含め、各言語のクライアントライブラリを使うためには認証が必要。認証にはサービスアカウントから発行するサービスアカウントキーが必要。サービスアカウントとは?

サービス アカウントは、ユーザーではなく、アプリケーションや仮想マシン(VM)インスタンスで使用される特別なアカウントです
https://cloud.google.com/iam/docs/service-accounts?hl=ja&_ga=2.25387837.-162766802.1631399405

認証を設定するの手順に沿って鍵を作成しダウンロードしておく。

Node.jsのfirestoreクライアントライブラリでデータベースを操作

Node.jsで実装していく。フォルダを作成しターミナルを開いたら、次のコマンドで先程の鍵のパスを環境変数に設定する。

linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="あなたのKEY_PATHの場所を設定"

実装

アプリにサーバー クライアント ライブラリを追加するを参考に実装する。

index.js
const Firestore = require('@google-cloud/firestore');

const main = async () => {
  try {

    const db = new Firestore({
      projectId: 'YOUR_PROJECT_ID',
      keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS
    })

    const docRef = db.collection('users').doc('alovelace');

    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });

    const aTuringRef = db.collection('users').doc('aturing');

    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });

    const snapshot = await db.collection('users').get()
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
  } catch (error) {
    console.error(error)
  }
}

main().catch(console.error)

実行

node index.js

Firebaseコンソールでチェックする。


参考

portgroundportground

CloudFirestoreのSDKの種類と用途(Web)

ここにまとまっていますが、firebase・firestoreの違いで混乱してきたのでまとめます。
https://firebase.google.com/docs/firestore/client/libraries

nodejs-firestore

先ほどのチュートリアルで使用したNode.jsサーバーSDK。CloudFirestoreへの管理アクセスを必要とする場合に使う。公開されているWebサイトでサイトからfirestoreに何かしらオペレーションしたい場合はこちらは使わない
https://github.com/googleapis/nodejs-firestore

If you are developing a Web or Node.js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK.
エンドユーザーに代わってCloudFirestoreにアクセスするWebまたはNode.jsアプリケーションを開発している場合は、firebase ClientSDKを使用してください。
https://github.com/googleapis/nodejs-firestore

疑問

エンドユーザーに代わってCloudFirestoreにアクセスするWebまたはNode.jsアプリケーションを開発している場合に使用すべき、firebase ClientSDKはどれか?わかったら追記します。