memo: Firebase ローカルの RealtimeDatabase に接続

ローカルで RealtimeDatabase を動かしてみたく、メモです。

- node -v v18.10.0
- npm -v 8.19.2
- firebase --version 11.23.1

# エミュレーター作成

- エミュレーター初期化実行
```
$ firebase init emulators

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  /xxxx/xxxx/emulator
```


- プロジェクト設定
```
=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

? Please select an option: 
  Use an existing project 
  Create a new project 
  Add Firebase to an existing Google Cloud Platform project 
❯ Don't set up a default project 
```

- デフォルトプロジェクト設定: 省略（結局後で設定してます・・）
```
? Please select an option: Don't set up a default project
```

- エミュレーター選択: Database Emulator
```
=== Emulators Setup
? Which Firebase emulators do you want to set up? Press Space to select 
emulators, then Enter to confirm your choices. (Press <space> to select, 
<a> to toggle all, <i> to invert selection, and <enter> to proceed)
 ◯ Authentication Emulator
 ◯ Functions Emulator
 ◯ Firestore Emulator
❯◉ Database Emulator
 ◯ Hosting Emulator
 ◯ Pub/Sub Emulator
 ◯ Storage Emulator
(Move up and down to reveal more choices)
```
- ポート： 9000
- emulator download Y
```
? Which Firebase emulators do you want to set up? Press Space to select 
emulators, then Enter to confirm your choices. Database Emulator
i  Port for database already configured: 9000
i  Emulator UI already enabled with port: (automatic)
? Would you like to download the emulators now? Yes
i  ui: downloading ui-v1.11.4.zip...

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

✔  Firebase initialization complete!
```

```作成されたfirebase.json
{
  "emulators": {
    "database": {
      "port": 9000
    },
    "ui": {
      "enabled": true
    },
    "singleProjectMode": true
  }
}
```

# エミュレーター起動

```
$ firebase emulators:start
```

```
i  emulators: Starting emulators: database
⚠  database: Did not find a Realtime Database rules file specified in a firebase.json config file. The emulator will default to allowing all reads and writes. Learn more about this option: https://firebase.google.com/docs/emulator-suite/install_and_configure#security_rules_configuration.
i  database: Database Emulator logging to database-debug.log
⚠  emulators: The Emulator UI is not starting, either because none of the emulated products have an interaction layer in Emulator UI or it cannot determine the Project ID. Pass the --project flag to specify a project.

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
└─────────────────────────────────────────────────────────────┘

┌──────────┬────────────────┐
│ Emulator │ Host:Port      │
├──────────┼────────────────┤
│ Database │ 127.0.0.1:9000 │
└──────────┴────────────────┘
  Emulator Hub not running.
  Other reserved ports: 4500

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


- [警告]カレントのプロジェクトが指定されていない旨の警告
```
⚠  emulators: The Emulator UI is not starting, either because none of the emulated products have an interaction layer in Emulator UI or it cannot determine the Project ID. Pass the --project flag to specify a project.
```
↓
```
プロジェクト設定
$ firebase use [Project ID]

Now using project [Project ID]
```

- カレントプロジェクト設定後
    - http://127.0.0.1:4000/ にてエミュレーターにアクセス可能に
```
i  emulators: Starting emulators: database
⚠  database: Did not find a Realtime Database rules file specified in a firebase.json config file. The emulator will default to allowing all reads and writes. Learn more about this option: https://firebase.google.com/docs/emulator-suite/install_and_configure#security_rules_configuration.
i  database: Database Emulator logging to database-debug.log
i  ui: downloading ui-v1.11.4.zip...
Progress: ========================================================================================> (100% of 4MB)
i  ui: Emulator UI logging to ui-debug.log

┌─────────────────────────────────────────────────────────────┐
│ ✔  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            │
├──────────┼────────────────┼────────────────────────────────┤
│ Database │ 127.0.0.1:9000 │ http://127.0.0.1:4000/database │
└──────────┴────────────────┴────────────────────────────────┘
  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.
```

- エミュレーターUI
![スクリーンショット 2023-03-23 9.04.41.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/119864/28f3c86e-11ec-64e2-d728-6fef5e2fd884.png)

- エミュレーターの RealtimeDatabase 操作
    - connectDatabaseEmulator で接続先を Emulator に
```firebase.tsx
import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_apiKey,
  authDomain: process.env.REACT_APP_authDomain,
  projectId: process.env.REACT_APP_projectId,
  storageBucket: process.env.REACT_APP_storageBucket,
  messagingSenderId: process.env.REACT_APP_messagingSenderId,
  appId: process.env.REACT_APP_appId,
  databaseURL: process.env.REACT_APP_database,
};

const app = initializeApp(firebaseConfig);
export const db = getDatabase(app);

if (process.env.NODE_ENV !== "production") {
  // エミュレーターに接続する
  connectDatabaseEmulator(db, "localhost", 9000);
}
```

- 書き込みできた！
![スクリーンショット 2023-03-23 9.28.19.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/119864/d0c8b9b6-7f9a-a713-82f5-bad86e95cfc6.png)