Firebase Emulator Suite を使用したローカル開発

1. 始める前に

Cloud Firestore や Cloud Functions などのサーバーレス バックエンド ツールは、非常に簡単に使用できますが、テストが難しい場合があります。Firebase Local Emulator Suite を使用すると、これらのサービスのローカル バージョンを開発マシンで実行できるため、アプリを迅速かつ安全に開発できます。

前提とする環境

  • Visual Studio Code、Atom、Sublime Text などのシンプルなエディタ
  • Node.js 10.0.0 以降(Node.js をインストールするには、nvm を使用し、バージョンを確認するには、node --version を実行します)
  • Java 7 以降(Java をインストールするには、こちらの手順に沿ってバージョンを確認してください。バージョンを確認するには、java -version を実行します)

演習内容

この Codelab では、複数の Firebase サービスを利用したシンプルなオンライン ショッピング アプリを実行し、デバッグします。

  • Cloud Firestore: リアルタイム機能を備えた、グローバルにスケーラブルなサーバーレスの NoSQL データベース。
  • Cloud Functions: イベントまたは HTTP リクエストに応答して実行されるサーバーレス バックエンド コード。
  • Firebase Authentication: 他の Firebase プロダクトと統合できるマネージド認証サービスです。
  • Firebase Hosting: ウェブアプリ向けの高速で安全なホスティング。

アプリを Emulator Suite に接続して、ローカルでの開発を可能にします。

2589e2f95b74fa88.png

また、次の方法についても説明します。

  • アプリを Emulator Suite に接続する方法と、さまざまなエミュレータの接続方法。
  • Firebase セキュリティ ルールの仕組みと、Firestore セキュリティ ルールをローカル エミュレータに対してテストする方法について説明します。
  • Firestore イベントによってトリガーされる Firebase Functions の関数を作成する方法と、Emulator Suite に対して実行する統合テストを作成する方法。

2. 設定

ソースコードを取得する

この Codelab では、完成間近の Fire Store サンプルのバージョンから始めます。そのため、まずはソースコードのクローンを作成する必要があります。

$ git clone https://github.com/firebase/emulators-codelab.git

次に、Codelab ディレクトリに移動します。このディレクトリで、この Codelab の残りの作業を行います。

$ cd emulators-codelab/codelab-initial-state

次に、コードを実行できるように依存関係をインストールします。インターネット接続が遅い場合は、1 ~ 2 分かかることがあります。

# Move into the functions directory
$ cd functions

# Install dependencies
$ npm install

# Move back into the previous directory
$ cd ../

Firebase CLI を取得する

Emulator Suite は Firebase CLI(コマンドライン インターフェース)の一部です。次のコマンドでマシンにインストールできます。

$ npm install -g firebase-tools

次に、CLI が最新バージョンであることを確認します。この Codelab はバージョン 9.0.0 以降で動作するはずですが、それ以降のバージョンには多くのバグ修正が含まれています。

$ firebase --version
9.6.0

Firebase プロジェクトに接続する

Firebase プロジェクトがない場合は、Firebase コンソールで新しい Firebase プロジェクトを作成します。選択したプロジェクト ID をメモしておきます。この ID は後で必要になります。

次に、このコードを Firebase プロジェクトに接続する必要があります。まず、次のコマンドを実行して Firebase CLI にログインします。

$ firebase login

次に、次のコマンドを実行してプロジェクト エイリアスを作成します。$YOUR_PROJECT_ID は、Firebase プロジェクトの ID に置き換えます。

$ firebase use $YOUR_PROJECT_ID

これでアプリを実行する準備が整いました。

3. エミュレータを実行する

このセクションでは、アプリをローカルで実行します。Emulator Suite を起動します。

エミュレータを起動する

Codelab のソース ディレクトリから、次のコマンドを実行してエミュレータを起動します。

$ firebase emulators:start --import=./seed

次のような出力が表示されます。

$ firebase emulators:start --import=./seed
i  emulators: Starting emulators: auth, functions, firestore, hosting
⚠  functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: database, pubsub
i  firestore: Importing data from /Users/samstern/Projects/emulators-codelab/codelab-initial-state/seed/firestore_export/firestore_export.overall_export_metadata
i  firestore: Firestore Emulator logging to firestore-debug.log
i  hosting: Serving hosting files from: public
✔  hosting: Local server: http://127.0.0.1:5000
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "/Users/samstern/Projects/emulators-codelab/codelab-initial-state/functions" for Cloud Functions...
✔  functions[calculateCart]: firestore function initialized.

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://127.0.0.1:4000                │
└─────────────────────────────────────────────────────────────┘

┌────────────────┬────────────────┬─────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Functions      │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Hosting        │ 127.0.0.1:5000 │ n/a                             │
└────────────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at 127.0.0.1:4400
  Other reserved ports: 4500

Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.

All Emulators started」というメッセージが表示されたら、アプリは使用可能です。

ウェブアプリをエミュレータに接続する

ログの表から、Cloud Firestore エミュレータがポート 8080 をリッスンし、Authentication エミュレータがポート 9099 をリッスンしていることがわかります。

┌────────────────┬────────────────┬─────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Functions      │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Hosting        │ 127.0.0.1:5000 │ n/a                             │
└────────────────┴────────────────┴─────────────────────────────────┘

フロントエンド コードを本番環境ではなくエミュレータに接続しましょう。public/js/homepage.js ファイルを開き、onDocumentReady 関数を見つけます。このコードが標準の Firestore インスタンスと Auth インスタンスにアクセスしていることがわかります。

public/js/homepage.js

  const auth = firebaseApp.auth();
  const db = firebaseApp.firestore();

db オブジェクトと auth オブジェクトを更新して、ローカル エミュレータを指すようにします。

public/js/homepage.js

  const auth = firebaseApp.auth();
  const db = firebaseApp.firestore();

  // ADD THESE LINES
  if (location.hostname === "127.0.0.1") {
    console.log("127.0.0.1 detected!");
    auth.useEmulator("http://127.0.0.1:9099");
    db.useEmulator("127.0.0.1", 8080);
  }

アプリがローカルマシンで実行されている(Hosting エミュレータによって処理)場合、Firestore クライアントは本番環境のデータベースではなくローカル エミュレータも参照します。

EmulatorUI を開く

ウェブブラウザで http://127.0.0.1:4000/ に移動します。Emulator Suite UI が表示されます。

エミュレータ UI ホーム画面

クリックすると、Firestore エミュレータの UI が表示されます。--import フラグを使用してインポートされたデータのため、items コレクションにはすでにデータが含まれています。

4ef88d0148405d36.png

4. アプリを実行する

アプリを開く

ウェブブラウザで http://127.0.0.1:5000 に移動すると、Fire Store がマシンのローカルで実行されていることがわかります。

939f87946bac2ee4.png

アプリを使用する

ホームページで商品を選択して [カートに追加] をクリックします。残念ながら、次のエラーが発生します。

a11bd59933a8e885.png

このバグを修正しましょう。すべてがエミュレータで実行されるため、実際のデータへの影響を心配することなく実験できます。

5. アプリをデバッグする

バグを見つける

それでは、Chrome デベロッパー コンソールを見てみましょう。Control+Shift+J(Windows、Linux、Chrome OS)または Command+Option+J(Mac)を押してコンソールにエラーを確認します。

74c45df55291dab1.png

addToCart メソッドでエラーが発生したようです。見てみましょう。このメソッドのどこで uid というものにアクセスしようとしていますか。なぜ null になるのでしょうか。現在、public/js/homepage.js のメソッドは次のようになります。

public/js/homepage.js

  addToCart(id, itemData) {
    console.log("addToCart", id, JSON.stringify(itemData));
    return this.db
      .collection("carts")
      .doc(this.auth.currentUser.uid)
      .collection("items")
      .doc(id)
      .set(itemData);
  }

アハ!アプリにログインしていません。Firebase Authentication のドキュメントによると、ログインしていない場合、auth.currentUsernull です。そのためのチェックを追加しましょう。

public/js/homepage.js

  addToCart(id, itemData) {
    // ADD THESE LINES
    if (this.auth.currentUser === null) {
      this.showError("You must be signed in!");
      return;
    }

    // ...
  }

アプリをテストする

ページを更新して、[カートに追加] をクリックします。今回は、より適切なエラーが表示されます。

c65f6c05588133f7.png

上部ツールバーの [ログイン] をクリックし、もう一度 [カートに追加] をクリックすると、カートが更新されます。

しかし、数値がまったく正確でないようです。

239f26f02f959eef.png

このバグはすぐに修正されます。まず、カートに商品を追加したときに実際に何が起きたかを詳しく見ていきましょう。

6. ローカル関数のトリガー

[Add to Cart] をクリックすると、複数のエミュレータに関わる一連のイベントが開始されます。カートに商品を追加すると、Firebase CLI のログで次のようなメッセージが記録されます。

i  functions: Beginning execution of "calculateCart"
i  functions: Finished "calculateCart" in ~1s

これらのログを生成するために、4 つの重要なイベントが発生しました。また、確認された UI の更新もありました。

68c9323f2ad10f7a.png

1)Firestore Write - クライアント

新しいドキュメントが Firestore コレクション /carts/{cartId}/items/{itemId}/ に追加されます。このコードは、public/js/homepage.js 内の addToCart 関数で確認できます。

public/js/homepage.js

  addToCart(id, itemData) {
    // ...
    console.log("addToCart", id, JSON.stringify(itemData));
    return this.db
      .collection("carts")
      .doc(this.auth.currentUser.uid)
      .collection("items")
      .doc(id)
      .set(itemData);
  }

2)Cloud Functions の関数がトリガーされる

Cloud Functions の関数 calculateCart は、functions/index.js で確認できる onWrite トリガーを使用して、カートの商品に対して発生する書き込みイベント(作成、更新、削除)をリッスンします。

functions/index.js

exports.calculateCart = functions.firestore
    .document("carts/{cartId}/items/{itemId}")
    .onWrite(async (change, context) => {
      try {
        let totalPrice = 125.98;
        let itemCount = 8;

        const cartRef = db.collection("carts").doc(context.params.cartId);

        await cartRef.update({
          totalPrice,
          itemCount
        });
      } catch(err) {
      }
    }
);

3)Firestore Write - 管理者

calculateCart 関数は、カート内のすべての商品を読み取り、合計数量と価格を合計してから、新しい合計で「cart」ドキュメントを更新します(上記の cartRef.update(...) を参照)。

4)Firestore Read - Client

ウェブ フロントエンドは、カートの変更に関する最新情報を受け取るよう登録されています。public/js/homepage.js でわかるように、Cloud Functions の関数が新しい合計を書き込んで UI を更新すると、リアルタイムで更新されます。

public/js/homepage.js

this.cartUnsub = cartRef.onSnapshot(cart => {
   // The cart document was changed, update the UI
   // ...
});

内容のまとめ

その調子です!3 種類の Firebase エミュレータを使用して完全なローカルテストを実施する、完全ローカルアプリをセットアップできました。

db82eef1706c9058.gif

他にもあります。次のセクションでは、以下の内容を学習します。

  • Firebase エミュレータを使用する単体テストを作成する方法。
  • Firebase エミュレータを使用してセキュリティ ルールをデバッグする方法。

7. アプリに合わせたセキュリティ ルールを作成

ウェブアプリはデータの読み取りと書き込みを行いますが、今のところセキュリティについてはまったく心配していません。Cloud Firestore は「セキュリティ ルール」と呼ばれるシステムを使用して、データの読み取りと書き込みにアクセスできるユーザーを宣言します。Emulator Suite は、このようなルールのプロトタイピングに最適です。

エディタで emulators-codelab/codelab-initial-state/firestore.rules ファイルを開きます。ルールには主に 3 つのセクションがあります。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // User's cart metadata
    match /carts/{cartID} {
      // TODO: Change these! Anyone can read or write.
      allow read, write: if true;
    }

    // Items inside the user's cart
    match /carts/{cartID}/items/{itemID} {
      // TODO: Change these! Anyone can read or write.
      allow read, write: if true;
    }

    // All items available in the store. Users can read
    // items but never write them.
    match /items/{itemID} {
      allow read: if true;
    }
  }
}

現在、誰でも当社のデータベースに対してデータを読み書きできます。Google は、有効なオペレーションのみが通過し、機密情報が漏洩しないようにしたいと考えています。

この Codelab では、最小権限の原則に従って、すべてのドキュメントをロックダウンし、すべてのユーザーが必要なすべてのアクセス権を得られるまで徐々にアクセス権を追加します。最初の 2 つのルールを更新して、アクセスを拒否する条件を false に設定します。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // User's cart metadata
    match /carts/{cartID} {
      // UPDATE THIS LINE
      allow read, write: if false;
    }

    // Items inside the user's cart
    match /carts/{cartID}/items/{itemID} {
      // UPDATE THIS LINE
      allow read, write: if false;
    }

    // All items available in the store. Users can read
    // items but never write them.
    match /items/{itemID} {
      allow read: if true;
    }
  }
}

8. エミュレータとテストを実行する

エミュレータを起動する

コマンドラインで、emulators-codelab/codelab-initial-state/ にいることを確認します。前の手順で使用したエミュレータが残っている可能性があります。実行されていない場合は、エミュレータを再起動します。

$ firebase emulators:start --import=./seed

エミュレータを実行したら、エミュレータに対してローカルでテストを実行できます。

テストを実行する

コマンドラインで、新しいターミナルタブemulators-codelab/codelab-initial-state/ ディレクトリから)

まず、関数ディレクトリに移動します(この Codelab の残りの部分はそのままです)。

$ cd functions

次に、functions ディレクトリで mocha テストを実行し、出力の一番上までスクロールします。

# Run the tests
$ npm test

> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha

  shopping carts
    1) can be created and updated by the cart owner
    2) can be read only by the cart owner

  shopping cart items
    3) can be read only by the cart owner
    4) can be added only by the cart owner

  adding an item to the cart recalculates the cart total. 
    - should sum the cost of their items


  0 passing (364ms)
  1 pending
  4 failing

現在のところ 4 件の失敗があります。ルールファイルを作成する際に、より多くのテストに合格するのを監視することで進行状況を測定できます。

9. 安全なカートアクセス

最初の 2 つの失敗は「ショッピング カート」テストで、次のことをテストします。

  • ユーザーは自分のカートのみを作成、更新できます
  • ユーザーは自分のカートのみを読み取ることができる

functions/test.js

  it('can be created and updated by the cart owner', async () => {
    // Alice can create her own cart
    await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").set({
      ownerUID: "alice",
      total: 0
    }));

    // Bob can't create Alice's cart
    await firebase.assertFails(bobDb.doc("carts/alicesCart").set({
      ownerUID: "alice",
      total: 0
    }));

    // Alice can update her own cart with a new total
    await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").update({
      total: 1
    }));

    // Bob can't update Alice's cart with a new total
    await firebase.assertFails(bobDb.doc("carts/alicesCart").update({
      total: 1
    }));
  });

  it("can be read only by the cart owner", async () => {
    // Setup: Create Alice's cart as admin
    await admin.doc("carts/alicesCart").set({
      ownerUID: "alice",
      total: 0
    });

    // Alice can read her own cart
    await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").get());

    // Bob can't read Alice's cart
    await firebase.assertFails(bobDb.doc("carts/alicesCart").get());
  });

これらのテストに合格するようにしましょう。エディタでセキュリティ ルールファイル firestore.rules を開き、match /carts/{cartID} 内のステートメントを更新します。

firestore.rules

rules_version = '2';
service cloud.firestore {
    // UPDATE THESE LINES
    match /carts/{cartID} {
      allow create: if request.auth.uid == request.resource.data.ownerUID;
      allow read, update, delete: if request.auth.uid == resource.data.ownerUID;
    }

    // ...
  }
}

カート所有者による読み取り / 書き込みアクセスのみがこれらのルールで許可されます。

受信データとユーザーの認証を検証するために、Google は各ルールのコンテキストで利用可能な 2 つのオブジェクトを使用します。

  • request オブジェクトには、試行されているオペレーションに関するデータとメタデータが含まれます。
  • Firebase プロジェクトで Firebase Authentication を使用している場合、request.auth オブジェクトはリクエストを行っているユーザーを記述します。

10. カートへのアクセスをテストする

Emulator Suite は、firestore.rules が保存されると自動的にルールを更新します。エミュレータを実行しているタブでメッセージ Rules updated を探すことで、エミュレータでルールが更新されたことを確認できます。

5680da418b420226.png

テストを再実行し、最初の 2 つのテストに合格することを確認します。

$ npm test

> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha

  shopping carts
    ✓ can be created and updated by the cart owner (195ms)
    ✓ can be read only by the cart owner (136ms)

  shopping cart items
    1) can be read only by the cart owner
    2) can be added only by the cart owner

  adding an item to the cart recalculates the cart total. 
    - should sum the cost of their items

  2 passing (482ms)
  1 pending
  2 failing

よくできました!これでショッピング カートへの安全なアクセスが可能になりました。次の失敗したテストを見てみましょう。

11. UI の「カートに追加」フローを確認する

現時点では、カートの所有者はカートに対して読み取り / 書き込みを行いますが、カート内の個々の商品に対して読み取り / 書き込みを行うことはできません。これは、オーナーはカート ドキュメントにアクセスできますが、カートのアイテム サブコレクションにはアクセスできないためです。

これはユーザーにとっては壊れた状態です。

http://127.0.0.1:5000, で実行されているウェブ UI に戻り、カートに商品を追加してみます。items サブコレクション内に作成されたドキュメントへのユーザー アクセス権がまだ付与されていないため、デバッグ コンソールに Permission Denied エラーが表示されます。

12. カート内のアイテムへのアクセスを許可する

次の 2 つのテストでは、ユーザーがカートへの商品の追加とカートからのアイテムの読み取りのみを行えることを確認します。

  it("can be read only by the cart owner", async () => {
    // Alice can read items in her own cart
    await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart/items/milk").get());

    // Bob can't read items in alice's cart
    await firebase.assertFails(bobDb.doc("carts/alicesCart/items/milk").get())
  });

  it("can be added only by the cart owner",  async () => {
    // Alice can add an item to her own cart
    await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart/items/lemon").set({
      name: "lemon",
      price: 0.99
    }));

    // Bob can't add an item to alice's cart
    await firebase.assertFails(bobDb.doc("carts/alicesCart/items/lemon").set({
      name: "lemon",
      price: 0.99
    }));
  });

そのため、現在のユーザーの UID がカート ドキュメントの所有者 UID と同じ場合にアクセスを許可するルールを作成できます。create, update, delete に別のルールを指定する必要はないため、write ルールを使用できます。このルールは、データを変更するすべてのリクエストに適用されます。

items サブコレクション内のドキュメントのルールを更新します。条件の get が Firestore から値(この場合は、カート ドキュメントの ownerUID)を読み取ります。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // ...

    // UPDATE THESE LINES
    match /carts/{cartID}/items/{itemID} {
      allow read, write: if get(/databases/$(database)/documents/carts/$(cartID)).data.ownerUID == request.auth.uid;
    }

    // ...
  }
}

13. カート内のアイテムへのアクセスをテストする

これでテストを再実行できます。出力の一番上までスクロールして、他のテストに合格することを確認します。

$ npm test

> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha

  shopping carts
    ✓ can be created and updated by the cart owner (195ms)
    ✓ can be read only by the cart owner (136ms)

  shopping cart items
    ✓ can be read only by the cart owner (111ms)
    ✓ can be added only by the cart owner


  adding an item to the cart recalculates the cart total. 
    - should sum the cost of their items


  4 passing (401ms)
  1 pending

問題なし。現在、すべてのテストに合格しています。保留中のテストが 1 つありますが、あと数ステップで完了します。

14. 「カートに追加」のフローをもう一度確認します。

ウェブ フロントエンド(http://127.0.0.1:5000)に戻り、カートに商品を追加します。これは、テストとルールがクライアントが必要とする機能に一致していることを確認する重要なステップです。(前回 UI を試したとき、ユーザーはカートに商品を追加できませんでした)。

69ad26cee520bf24.png

firestore.rules が保存されると、クライアントは自動的にルールを再読み込みします。カートに商品を追加してみましょう

内容のまとめ

お疲れさまでした。アプリのセキュリティを強化できました。これは、アプリを本番環境で使用できる状態にするための重要なステップです。これが本番環境アプリであれば、これらのテストを継続的インテグレーション パイプラインに追加できます。そうすれば、たとえ他のユーザーがルールを変更したとしても、今後はショッピング カートのデータにこれらのアクセス制御が適用されることを確信できます。

ba5440b193e75967.gif

他にもあります

このまま続けると、次のことが学べます。

  • Firestore イベントによってトリガーされる関数を作成する方法
  • 複数のエミュレータで動作するテストを作成する方法

15. Cloud Functions のテストを設定する

ここまでは、ウェブアプリのフロントエンドと Firestore セキュリティ ルールに焦点を当ててきました。しかし、このアプリは Cloud Functions を使用してユーザーのカートを最新の状態に保つため、このコードもテストします。

Emulator Suite を使用すると、Cloud Functions を簡単にテストできます。Cloud Firestore やその他のサービスを使用する関数もテストできます。

エディタで emulators-codelab/codelab-initial-state/functions/test.js ファイルを開き、ファイル内の最後のテストまでスクロールします。現在、ステータスは保留中としてマークされています。

//  REMOVE .skip FROM THIS LINE
describe.skip("adding an item to the cart recalculates the cart total. ", () => {
  // ...

  it("should sum the cost of their items", async () => {
    ...
  });
});

テストを有効にするには、次のように .skip を削除します。

describe("adding an item to the cart recalculates the cart total. ", () => {
  // ...

  it("should sum the cost of their items", async () => {
    ...
  });
});

次に、ファイルの先頭にある REAL_FIREBASE_PROJECT_ID 変数を探し、実際の Firebase プロジェクト ID に変更します。

// CHANGE THIS LINE
const REAL_FIREBASE_PROJECT_ID = "changeme";

プロジェクト ID を忘れた場合は、Firebase コンソールのプロジェクト設定で Firebase プロジェクト ID を確認できます。

d6d0429b700d2b21.png

16. Functions のテストについて確認する

このテストでは Cloud Firestore と Cloud Functions のインタラクションを検証するため、前の Codelab のテストよりも多くの設定が必要になります。このテストを順を追って、どのような結果になるか見てみましょう。

カートを作成する

Cloud Functions は信頼できるサーバー環境で実行され、Admin SDK で使用されるサービス アカウント認証を使用できます。まず、initializeApp ではなく initializeAdminApp を使用してアプリを初期化します。次に、商品を追加するカートの DocumentReference を作成し、カートを初期化します。

it("should sum the cost of their items", async () => {
    const db = firebase
        .initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
        .firestore();

    // Setup: Initialize cart
    const aliceCartRef = db.doc("carts/alice")
    await aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });

    ...
  });

関数をトリガーする

次に、関数をトリガーするために、カート ドキュメントの items サブコレクションにドキュメントを追加します。2 つの項目を追加して、関数内で行われる加算をテストしていることを確認します。

it("should sum the cost of their items", async () => {
    const db = firebase
        .initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
        .firestore();

    // Setup: Initialize cart
    const aliceCartRef = db.doc("carts/alice")
    await aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });

    //  Trigger calculateCart by adding items to the cart
    const aliceItemsRef = aliceCartRef.collection("items");
    await aliceItemsRef.doc("doc1").set({name: "nectarine", price: 2.99});
    await aliceItemsRef.doc("doc2").set({ name: "grapefruit", price: 6.99 });

    ...
    });
  });

テストの期待値を設定する

onSnapshot() を使用して、カート ドキュメントの変更に対するリスナーを登録します。onSnapshot() は、リスナーの登録を解除するために呼び出すことができる関数を返します。

このテストでは、合計で 9.98 ドルのアイテムを 2 つ追加します。次に、カートに itemCounttotalPrice が含まれているかどうかを確認します。もしそうならば、関数はその役割を果たしています。

it("should sum the cost of their items", (done) => {
    const db = firebase
        .initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
        .firestore();

    // Setup: Initialize cart
    const aliceCartRef = db.doc("carts/alice")
    aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });

    //  Trigger calculateCart by adding items to the cart
    const aliceItemsRef = aliceCartRef.collection("items");
    aliceItemsRef.doc("doc1").set({name: "nectarine", price: 2.99});
    aliceItemsRef.doc("doc2").set({ name: "grapefruit", price: 6.99 });
    
    // Listen for every update to the cart. Every time an item is added to
    // the cart's subcollection of items, the function updates `totalPrice`
    // and `itemCount` attributes on the cart.
    // Returns a function that can be called to unsubscribe the listener.
    await new Promise((resolve) => {
      const unsubscribe = aliceCartRef.onSnapshot(snap => {
        // If the function worked, these will be cart's final attributes.
        const expectedCount = 2;
        const expectedTotal = 9.98;
  
        // When the `itemCount`and `totalPrice` match the expectations for the
        // two items added, the promise resolves, and the test passes.
        if (snap.data().itemCount === expectedCount && snap.data().totalPrice == expectedTotal) {
          // Call the function returned by `onSnapshot` to unsubscribe from updates
          unsubscribe();
          resolve();
        };
      });
    });
   });
 });

17. テストを実行する

以前のテストで実行されたエミュレータが残っている可能性があります。実行されていない場合は、エミュレータを起動します。コマンドラインから

$ firebase emulators:start --import=./seed

新しいターミナルタブを開き(エミュレータを実行したままにして)、functions ディレクトリに移動します。セキュリティ ルールのテストでまだ開いている可能性があります。

$ cd functions

単体テストを実行すると、合計 5 つのテストが表示されます。

$ npm test

> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha

  shopping cart creation
    ✓ can be created by the cart owner (82ms)

  shopping cart reads, updates, and deletes
    ✓ cart can be read by the cart owner (42ms)

  shopping cart items
    ✓ items can be read by the cart owner (40ms)
    ✓ items can be added by the cart owner

  adding an item to the cart recalculates the cart total. 
    1) should sum the cost of their items

  4 passing (2s)
  1 failing

具体的なエラーを見ると、タイムアウト エラーのように見えます。これは、関数が正しく更新されるのをテストが待機しているにもかかわらず、更新されないからです。これで、テストの要件を満たす関数を作成する準備が整いました。

18. 関数を作成する

このテストを修正するには、functions/index.js の関数を更新する必要があります。この関数の一部は記述されていますが、完全ではありません。関数の現在の動作は次のとおりです。

// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
    .firestore.document("carts/{cartId}/items/{itemId}")
    .onWrite(async (change, context) => {
      console.log(`onWrite: ${change.after.ref.path}`);
      if (!change.after.exists) {
        // Ignore deletes
        return;
      }

      let totalPrice = 125.98;
      let itemCount = 8;
      try {
        
        const cartRef = db.collection("carts").doc(context.params.cartId);

        await cartRef.update({
          totalPrice,
          itemCount
        });
      } catch(err) {
      }
    });

この関数はカート参照を正しく設定していますが、totalPriceitemCount の値を計算する代わりに、ハードコードされた値に更新します。

Cloud Functions の関数を

items サブコレクション

新しい定数 itemsSnap を初期化して、items サブコレクションにします。次に、コレクション内のすべてのドキュメントを反復処理します。

// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
    .firestore.document("carts/{cartId}/items/{itemId}")
    .onWrite(async (change, context) => {
      console.log(`onWrite: ${change.after.ref.path}`);
      if (!change.after.exists) {
        // Ignore deletes
        return;
      }


      try {
        let totalPrice = 125.98;
        let itemCount = 8;

        const cartRef = db.collection("carts").doc(context.params.cartId);
        // ADD LINES FROM HERE
        const itemsSnap = await cartRef.collection("items").get();

        itemsSnap.docs.forEach(item => {
          const itemData = item.data();
        })
        // TO HERE
       
        return cartRef.update({
          totalPrice,
          itemCount
        });
      } catch(err) {
      }
    });

totalPrice と itemCount を計算する

まず、totalPriceitemCount の値をゼロに初期化しましょう。

次に、ロジックを反復ブロックに追加します。まず、商品アイテムに価格が指定されていることを確認します。アイテムに数量が指定されていない場合は、デフォルトの 1 が使用されます。次に、その数量を合計 itemCount に追加します。最後に、アイテムの価格に数量を掛けた値を合計 totalPrice に追加します。

// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
    .firestore.document("carts/{cartId}/items/{itemId}")
    .onWrite(async (change, context) => {
      console.log(`onWrite: ${change.after.ref.path}`);
      if (!change.after.exists) {
        // Ignore deletes
        return;
      }

      try {
        // CHANGE THESE LINES
        let totalPrice = 0;
        let itemCount = 0;

        const cartRef = db.collection("carts").doc(context.params.cartId);
        const itemsSnap = await cartRef.collection("items").get();

        itemsSnap.docs.forEach(item => {
          const itemData = item.data();
          // ADD LINES FROM HERE
          if (itemData.price) {
            // If not specified, the quantity is 1
            const quantity = itemData.quantity ? itemData.quantity : 1;
            itemCount += quantity;
            totalPrice += (itemData.price * quantity);
          }
          // TO HERE
        })

        await cartRef.update({
          totalPrice,
          itemCount
        });
      } catch(err) {
      }
    });

ロギングを追加して、成功状態とエラー状態をデバッグすることもできます。

// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
    .firestore.document("carts/{cartId}/items/{itemId}")
    .onWrite(async (change, context) => {
      console.log(`onWrite: ${change.after.ref.path}`);
      if (!change.after.exists) {
        // Ignore deletes
        return;
      }

      let totalPrice = 0;
      let itemCount = 0;
      try {
        const cartRef = db.collection("carts").doc(context.params.cartId);
        const itemsSnap = await cartRef.collection("items").get();

        itemsSnap.docs.forEach(item => {
          const itemData = item.data();
          if (itemData.price) {
            // If not specified, the quantity is 1
            const quantity = (itemData.quantity) ? itemData.quantity : 1;
            itemCount += quantity;
            totalPrice += (itemData.price * quantity);
          }
        });

        await cartRef.update({
          totalPrice,
          itemCount
        });

        // OPTIONAL LOGGING HERE
        console.log("Cart total successfully recalculated: ", totalPrice);
      } catch(err) {
        // OPTIONAL LOGGING HERE
        console.warn("update error", err);
      }
    });

19. テストを再実行する

コマンドラインで、エミュレータがまだ実行中であることを確認してから、テストを再実行します。エミュレータを再起動する必要はありません。エミュレータは関数の変更内容を自動的に取得します。すべてのテストに合格するはずです。

$ npm test
> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha

  shopping cart creation
    ✓ can be created by the cart owner (306ms)

  shopping cart reads, updates, and deletes
    ✓ cart can be read by the cart owner (59ms)

  shopping cart items
    ✓ items can be read by the cart owner
    ✓ items can be added by the cart owner

  adding an item to the cart recalculates the cart total. 
    ✓ should sum the cost of their items (800ms)


  5 passing (1s)

よくできました!

20. ストアフロント UI で試す

最後のテストとして、ウェブアプリ(http://127.0.0.1:5000/)に戻り、商品をカートに追加します。

69ad26cee520bf24.png

カートが更新され、正しい合計値になっていることを確認します。ではさっそく、

内容のまとめ

Cloud Functions for Firebase と Cloud Firestore の複雑なテストケースを見てきました。テストに合格する Cloud Functions の関数を記述しました。また、新機能が UI で動作することも確認しました。このすべてをローカルで行い、自分のマシンでエミュレータを実行しました。

また、ローカル エミュレータに対して実行するウェブ クライアントを作成し、データを保護するためのセキュリティ ルールを調整して、ローカル エミュレータを使用してセキュリティ ルールをテストしました。

c6a7aeb91fe97a64.gif