Firebase 如何写入firestore emulator?

Firebase 如何写入firestore emulator?,firebase,google-cloud-firestore,google-cloud-functions,firebase-cli,Firebase,Google Cloud Firestore,Google Cloud Functions,Firebase Cli,我正在开发一个firebase云函数,用于写入firestore数据库 在开发过程中,我希望函数写入本地数据库。所以我启动了一个firestore模拟器。但是数据仍然被写入到实际的数据库中 如何配置云功能以使用本地数据库 这是我的设置: import*作为“firebase函数”中的函数; 从“cors”导入*作为cors; 从“firebase管理员”导入*作为管理员; const REGION=“欧洲西部1”; const COLLECTION\u CONTACT\u FORM=“CONTA

我正在开发一个firebase云函数,用于写入firestore数据库

在开发过程中,我希望函数写入本地数据库。所以我启动了一个firestore模拟器。但是数据仍然被写入到实际的数据库中

如何配置云功能以使用本地数据库

这是我的设置:

import*作为“firebase函数”中的函数;
从“cors”导入*作为cors;
从“firebase管理员”导入*作为管理员;
const REGION=“欧洲西部1”;
const COLLECTION\u CONTACT\u FORM=“CONTACT\u FORM”;
const servicecomport=require(“../keys/auth key.json”);
admin.initializeApp({
凭证:admin.credential.cert(serviceAccount)
});
const corsMiddleware=cors({origin:true});
export const sendContactForm=functions.region(region).https.onRequest((请求,响应)=>corsmidware(请求,响应,异步()=>{
让{text}=request.body;
让result=wait admin.firestore().collection(collection\u CONTACT\u FORM).add({text});
response.send((result.id));
}));
这是启动仿真器时的控制台输出:

[1] i  firestore: Serving WebChannel traffic on at http://localhost:8081
[1] i  firestore: Emulator logging to firestore-debug.log
[1] ✔  functions: Emulator started at http://localhost:5000
[1] ✔  firestore: Emulator started at http://localhost:8080
[1] i  functions: Watching "path/functions" for Cloud Functions...
[1] ⚠  functions: Your GOOGLE_APPLICATION_CREDENTIALS environment variable points to path/keys/auth-key.json. Non-emulated services will access production using these credentials. Be careful!
[1] ✔  functions[sendContactForm]: http function initialized (http://localhost:5000/project/europe-west1/sendContactForm).

触发本地终结点时,生产数据库将写入。

firestore管理员
initializeApp()
将根据运行位置正确处理本地仿真器和生产数据库之间的切换。因此,如果您只是删除服务帐户凭据,它应该可以正常工作:

import * as functions from 'firebase-functions';
import * as cors from "cors";
import * as admin from "firebase-admin";

const REGION = "europe-west1";
const COLLECTION_CONTACT_FORM = "contact_form";

admin.initializeApp();
const corsMiddleware = cors({origin: true});

export const sendContactForm = functions.region(REGION).https.onRequest((request, response) => corsMiddleware(request, response, async () => {
    let {text} = request.body;
    let result = await admin.firestore().collection(COLLECTION_CONTACT_FORM).add({text});
    response.send((result.id));
}));
但是,如果出于某种原因,您试图在创建项目的firestore数据库之外写入firestore数据库,则可以将firestore/grpc与firebase类分开使用,然后使用环境包含您的服务帐户凭据或位置仿真器凭据。本地仿真器示例:

const {Firestore} = require('@google-cloud/firestore');
const {credentials} = require('@grpc/grpc-js');

const db = new Firestore({
  projectId: 'my-project-id',
  servicePath: 'localhost',
  port: 5100,
  sslCreds: credentials.createInsecure(),
  customHeaders: {
    "Authorization": "Bearer owner"
  }
});

await db.collection("mycollection").doc("someid").set({ test: "value" });