如何触发将写入数据复制到其他Firestore中的集合的onwrite

时间:2019-05-05 22:46:07

标签: google-cloud-firestore google-cloud-functions

出于安全考虑,我想拥有两个Firestore实例。一个是主要数据,另一个只是第一个数据的一部分。我的问题是,在第一个实例中执行onWrite之后,如何触发对第二个Firestore实例的写入。甚至可行吗?

这是我的云功能中的内容:

"use strict";

const functions = require("firebase-functions");
const admin = require('./admin');

try {admin.initializeApp(functions.config().firebase);} catch(e) {} 

const firebaseConfig2 = {
  apiKey: "xxx",
  authDomain: "xxx.firebaseapp.com",
  databaseURL: "https://xxx.firebaseio.com",
  projectId: "xxx",
  storageBucket: "xxx.appspot.com",
  messagingSenderId: "xxx",
  appId: "1:xxx:web:xxx"
};

var xxx2 = admin.initializeApp(firebaseConfig2, 'xxx2');

const db2 = xxx2.database();

exports = module.exports = functions.firestore
  .document("doc/{docId}")
  .onWrite((change, context) => {
    let newDoc = change.after.data();
    return newDoc == xxx2
      .collection("newcol")
      .doc(context.params.docId)
      .set(newDoc, { merge: true });
  });

如果为true,则xxx2侧的规则为可读/可写;

但是,在db1端出现此错误:

@firebase/database: FIREBASE WARNING: Provided authentication credentials for the app named "xxx2" are invalid. This usually indicates your app was not initialized correctly. Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project. 

凭据已从console.firebase项目xxx2设置中获取。他们错了吗?我应该改用哪个?

1 个答案:

答案 0 :(得分:0)

经过反复试验,我找到了解决方案。它是要使用与上面的配置不同的firebase配置-在设置和服务帐户下在firebase中可用的私有配置-生成私有密钥。与公共密钥不同,它应该包含您的私钥等,并且您只需要在后端保留它即可。

此外,将两个管理配置提取到单独的文件中也是有意义的,只有在需要的地方才将它们加载到函数中:

const admin = require('./admin');
const admin2 = require('./admin2');