12
1

More than 3 years have passed since last update.

Firebase Emulatorsのデータを永続化する

Posted at

私は普段の開発でBaaS(Backend as a Service)を使うことはほとんどありませんが、最近は少しFirebaseを使っています。Firebaseには各種エミュレータが備わっていて、Firestoreなどわざわざクラウドに接続しなくても、ローカルで起動したエミュレータに接続するようにして開発に役立てることができます。

firebase-tools を設定済みの環境で、以下のコマンドを実行すればエミュレータを起動できます。簡単ですね :sparkles:

$ npx firebase emulators:start

通常、エミュレータを使って開発を進めますが、上記のコマンドで起動すると停止した際にデータがすべて消えてしまいます。どうしたものかと思って調べたところ、以下のイシューを見つけました。 --import--export-on-exit オプションを付けて起動すれば、エミュレータ停止時に指定したディレクトリにデータが保存され、次回起動時に保存済みのデータが使われるようになるんだと。

例えば data というディレクトリに保存したければ、

$ npx firebase emulators:start --import data --export-on-exit

このように実行すればOKです。

と、ここまでの内容は、実はすべて公式ドキュメントやコマンドのヘルプに載っています。ちゃんと読みましょうってことですね :sweat_smile:

$ npx firebase emulators:start --help
実行結果
Usage: firebase emulators:start [options]

start the local Firebase emulators

Options:
  --only <emulators>          only specific emulators. This is a comma separated list of emulator names. Valid options are: ["auth","functions","firestore","database","hosting","pubsub","storage"]
  --inspect-functions [port]  emulate Cloud Functions in debug mode with the node inspector on the given port (9229 if not specified)
  --import [dir]              import emulator data from a previous export (see emulators:export)
  --export-on-exit [dir]      automatically export emulator data (emulators:export) when the emulators make a clean exit (SIGINT), when no dir is provided the location of --import [dir] is used
  -h, --help                  output usage information

ディレクトリの指定に関するちょっとした注意点

出力先として data ディレクトリを指定した場合、以下のようなディレクトリ構造で出力されます。

data
├── firebase-export-metadata.json
├── firestore_export
│   ├── all_namespaces
│   └── firestore_export.overall_export_metadata
└── storage_export
    ├── blobs
    ├── buckets.json
    └── metadata

このとき、 data ディレクトリは勝手に生成されますが、ログを見る限り単純に mkdir $PWD/data を実行しているだけのようです。ディレクトリの階層を増やそうとして、 data ディレクトリがない状態で data/firebase のような指定をしてしまうと、ディレクトリの生成に失敗してデータが出力されないので注意が必要です :point_up:

12
1
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
12
1