gpt4 book ai didi

firebase - 如何写入firestore模拟器?

转载 作者:行者123 更新时间:2023-12-02 02:43:16 24 4
gpt4 key购买 nike

我正在开发一个写入 firestore 数据库的 firebase 云函数。

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

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

这是我的设置:

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";

const serviceAccount = require("../keys/auth-key.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});

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));
}));

这是启动模拟器时的控制台输出:
[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/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" });

关于firebase - 如何写入firestore模拟器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57790978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com