LoginSignup
36
22

More than 3 years have passed since last update.

Go + Firestore (サーバー側) でローカルエミュレーターを使ってテストする

Last updated at Posted at 2019-03-21

要約

  • Cloud Firestore のローカルエミュレーターは Go でも使える
  • gcloud beta emulators firestore start した後に環境変数 FIRESTORE_EMULATOR_HOST をセットするだけ

きっかけ

Firebase の超便利なデータストアサービス Cloud Firestore 、ついにGAになって東京リージョンもきて最近熱いサービスです!

しかし、クラウド系のサービスはローカル開発やテストをしたいときにどうやってやるか悩みがちです。大抵次のどちらかになる印象です。

  • ローカルで起動できるエミュレーターなどを使う
  • テスト専用のクラウドリソースを作っておいて、毎回そこに接続する

Cloud Firestore にはローカルエミュレーターがある

幸い Firestore にはローカルエミュレーターがあります。google-cloud-jpにわかりやすい記事があがっているので、こちらも参照するとよいでしょう。

Firestore ローカルエミュレーターを試してみた。 – google-cloud-jp – Medium

Node.js しか対応してない・・・?

しかし、公式ドキュメントを読んでみると…

現在エミュレータをサポートしている唯一の SDK は Node.js SDK です。エミュレータとのやりとりを容易にするために、@firebase/testing モジュールを用意しました。

Node.js 以外のランタイムでは使えなさそうです。残念ですね。

Go でもローカルエミュレーターが使える

自分は最初 Go をつかって Firestore をサーバー側から操作するプログラムを書いてたので、「Node.js しか使えないのか…残念だなぁ」と思いました。

しかし、Go のライブラリのドキュメントを読んでいると…

This package supports the Cloud Firestore emulator, which is useful for testing and development. Environment variables are used to indicate that Firestore traffic should be directed to the emulator instead of the production Firestore service.

To install and run the emulator and its environment variables, see the documentation at https://cloud.google.com/sdk/gcloud/reference/beta/emulators/firestore/. Once the emulator is running, set FIRESTORE_EMULATOR_HOST to the API endpoint.

Node.js だけではなくて、Go でも使えるじゃん!!!!!

image.png

使い方

Go のドキュメントに書いてある通りです。 gcloud beta emulators firestore start で指定のポート番号でローカルエミュレーターを立ち上げできます。

$ gcloud beta emulators firestore start --host-port=localhost:8812

Executing: ../google-cloud-sdk/platform/cloud-firestore-emulator/cloud_firestore_emulator start --host=localhost --port=8812
[firestore] API endpoint: http://localhost:8812
[firestore] If you are using a library that supports the FIRESTORE_EMULATOR_HOST environment variable, run:
[firestore] 
[firestore]    export FIRESTORE_EMULATOR_HOST=localhost:8812
[firestore] 
[firestore] Dev App Server is now running.
[firestore] 

あとは、↑の出力にも書かれている通り、環境変数 FIRESTORE_EMULATOR_HOST にセットしてあげると、Go の Firestore ライブラリはエミュレーターの方につなぎにいくようになります。

package main

import (
    "context"
    "cloud.google.com/go/firestore"
    "log"
)

func main() {
    ctx := context.Background()

    // firebase projectIDは適当でOK
    store, err := firestore.NewClient(ctx, "testing")
    if err != nil {
        log.Fatal(err)
    }
    doc, _, err := store.Collection("users").Add(ctx, map[string]interface{}{
        "name": "hello",
    });
    if err != nil {
        log.Fatal(err)
    }
    println(doc.ID)
}

これでテスト専用の Firestore を作らなくても、気軽にテストが実行できる環境ができました。便利ですね! :smile:

36
22
2

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
36
22