如何将云Firestore中的数据导入本地模拟器?

How to import data from cloud firestore to the local emulator?

我希望能够 运行 在本地使用云功能并根据生产数据的副本进行调试。 有没有办法将在线的数据复制到本地firestore模拟器?

没有将数据从云项目复制到本地模拟器的内置方法。由于模拟器不会保留任何数据,因此您必须在每个 运行.

上重新生成初始数据集

您可以使用 firestore-backup-restore 将生产数据作为 JSON 文件导出和导入。

我写了一个快速 hack 以允许在 Firebase Simulator Firestore 实例中导入这些 JSON。

我提出了一个拉取请求并同时提出了这个 npm module

你可以这样使用它:

const firestoreService = require('@crapougnax/firestore-export-import')
const path = require('path')

// list of JSON files generated with the export service
// Must be in the same folder as this script
const collections = ['languages', 'roles']

// Start your firestore emulator for (at least) firestore
// firebase emulators:start --only firestore

// Initiate Firebase Test App
const db = firestoreService.initializeTestApp('test', {
   uid: 'john',
   email: 'john@doe.com',
})

// Start importing your data
let promises = []
try {
   collections.map(collection =>
      promises.push(
         firestoreService.fixtures(
            path.resolve(__dirname, `./${collection}.json`),
            [],
            [],
            db,
         ),
      ),
   )
   Promise.all(promises).then(process.exit)
} catch (err) {
   console.error(err)
}

显然,由于此数据不会保留在模拟器中,因此您通常会将它们注入到测试套件的 before() 函数中,甚至在每次测试之前。

我能够制作一些 npm 脚本以从远程导入到本地模拟器,反之亦然。

"serve": "yarn build && firebase emulators:start --only functions,firestore --import=./firestore_export",
"db:update-local-from-remote": "yarn db:backup-remote && gsutil -m cp -r gs://my-firebase-bucket.appspot.com/firestore_export .",
"db:update-remote-from-local": "yarn db:backup-local && yarn db:backup-remote && gsutil -m cp -r ./firestore_export gs://my-firebase-bucket.appspot.com && yarn run db:import-remote",
"db:import-remote": "gcloud firestore import gs://my-firebase-bucket.appspot.com/firestore_export",
"db:backup-local": "firebase emulators:export --force .",
"db:rename-remote-backup-folder": "gsutil mv gs://my-firebase-bucket.appspot.com/firestore_export gs://my-firebase-bucket.appspot.com/firestore_export_$(date +%d-%m-%Y-%H-%M)",
"db:backup-remote": "yarn db:rename-remote-backup-folder && gcloud firestore export gs://my-firebase-bucket.appspot.com/firestore_export"

因此您可以将本地 Firestore 数据导出到远程:

npm db:update-remote-from-local

或者要使用远程 Firestore 更新本地 Firestore 数据,请执行以下操作:

npm db:update-local-from-remote

这些操作将备份远程 Firestore 数据,制作一份副本并将其存储在 Firebase 存储中。

我的方法有点手动,但它确实有效。我已经在 this useful Github thread 中分享了它,但如果您觉得它们有用,我会在此处列出我执行的步骤:

  1. 转到我本地的 Firebase 项目路径。
  2. 使用以下命令启动模拟器:firebase emulators:start
  3. 使用提供的按钮在 http://localhost:4000/firestore 使用 GUI 手动创建一些模型数据:+ 开始收集+ 添加文档.
  4. 使用以下方法在本地导出此数据: emulators:export ./mydirectory
  5. 关于位于 Firebase 数据库/Cloud Firestore 的项目数据,我导出了一个这样的集合:gcloud firestore export gs://my-project-bucket-id.appspot.com --collection-ids=myCollection 导出现在位于 Firebase 存储 在一个以时间戳为名称的文件夹中(我没有为我的测试使用前缀)
  6. 使用以下命令将此文件夹下载到本地驱动器:gsutil cp -r gs://my-project-bucket-id.appspot.com/myCollection ./production_data_export 注意:我在 Windows 环境中执行此操作... gsutil 将抛出此错误: “OSError:文件名、目录名或卷标语法不正确” 如果文件夹在 Windows 中包含文件夹名称的无效字符(即冒号)或此错误: "OSError: Invalid argument.9.0 B]" 如果文件夹中的内部文件也包含无效字符。为了能够在本地下载导出,请使用有效的 Windows 名称重命名它们(即删除冒号),如下所示:gsutil mv gs://my-project-bucket-id.appspot.com/2020-05-22T02:01:06_86152 gs://my-project-bucket-id.appspot.com/myCollection
  7. 下载后,模仿本地导出结构将文件夹重命名为firestore_export并从本地导出文件夹复制firebase-export-metadata.json文件。为了直观起见,这是我得到的结构:
$ tree .
.
├── local_data_export
│   ├── firebase-export-metadata.json
│   └── firestore_export
│       ├── all_namespaces
│       │   └── all_kinds
│       │       ├── all_namespaces_all_kinds.export_metadata
│       │       └── output-0
│       └── firestore_export.overall_export_metadata
└── production_data_export
    ├── firebase-export-metadata.json
    └── firestore_export
        ├── all_namespaces
        │   └── kind_myCollection
        │       ├── all_namespaces_kind_myCollection.export_metadata
        │       ├── output-0
        │       └── output-1
        └── firestore_export.overall_export_metadata

8 directories, 9 files
  1. 最后,启动本地模拟器指向这个要导入的生产数据:firebase emulators:start --import=./mock_up_data/production_data_export/
  2. 您应该会在以下位置看到导入的数据:http://localhost:4000/firestore/

目前这应该对读者有所帮助,同时我们等待 Firebase 人员提供更强大的解决方案。

这可以通过现有项目的终端中的一组命令来完成:

1.登录 firebase 和 Gcloud:

firebase login
gcloud auth login

2。查看您的项目列表并连接到其中一个项目:

firebase projects:list
firebase use your-project-name

gcloud projects list
gcloud config set project your-project-name

3。使用所选名称将您的生产数据导出到 gcloud 存储桶:

gcloud firestore export gs://your-project-name.appspot.com/your-choosen-folder-name

4.现在将此文件夹复制到您的本地计算机,我直接在函数文件夹中执行此操作:

cd functions
gsutil -m cp -r gs://your-project-name.appspot.com/your-choosen-folder-name .

5.现在我们只想导入这个文件夹。由于 Firebase 团队 https://github.com/firebase/firebase-tools/pull/2519.

的最新更新,这应该适用于基本命令
firebase emulators:start --import ./your-choosen-folder-name

查看我在 Medium 上关于它的文章和一个速记脚本来为您完成这项工作 https://medium.com/firebase-developers/how-to-import-production-data-from-cloud-firestore-to-the-local-emulator-e82ae1c6ed8

注意:最好为它使用不同的存储桶,因为复制到您的项目存储桶将导致在您的 firebase 存储中创建文件夹。
如果您对 -m 等 gsutil 参数感兴趣,可以通过执行 gsutil --help.

查看它们的描述

我正要为 firebase-tools but pretty happy with the node-firestore-import-export 包添加一个 cli 选项。

yarn add -D node-firestore-import-export
  "scripts": {
    "db:export": "firestore-export -a ./serviceAccountKey.json -b ./data/firestore.json",
    "db:import": "firestore-import -a ./serviceAccountKey.json -b ./data/firestore.json",
    "db:emulator:export": "export FIRESTORE_EMULATOR_HOST=localhost:8080 && yarn db:export",
    "db:emulator:import": "export FIRESTORE_EMULATOR_HOST=localhost:8080 && yarn db:import",
    "db:backup": "cp ./data/firestore.json ./data/firestore-$(date +%d-%m-%Y-%H-%M).json",
    "dev": "firebase emulators:start --import=./data --export-on-exit=./data",
  },

您需要在 firebase 控制台中创建一个服务帐户。

您可以用硬编码值替换 GCLOUD_PROJECT 环境变量。

open https://console.firebase.google.com/project/$GCLOUD_PROJECT/settings/serviceaccounts/adminsdk
mv ~/Downloads/myProjectHecticKeyName.json ./serviceAccountKey.json

话虽如此,gcloud 工具绝对是生产环境的最佳选择,因为无论如何您都需要 s3 备份。

我写了一个小脚本来做到这一点:

const db = admin.firestore();
const collections = ['albums', 'artists'];
let rawData: any;
    
for (const i in collections) {
    rawData = fs.readFileSync(`./${collections[i]}.json`);
    const arr = JSON.parse(rawData);

    for (const j in arr) {
        db.collection(collections[i]).add(arr[j])
        .then(val => console.log(val))
        .catch(err => console.log('ERRO: ', err))
    }
        
}

我已经创建了 fire-import npm 包,用于将 firebase firestorefirebase storage 导入本地模拟器。

我在后台使用了 gcloud sdk cli。我知道实施并不完美。但我希望这个包能帮助您轻松导入 firestore 和 firebase 存储。祝您使用包愉快。