0
votes

I'd like to have two firestore instances for security reasons. One being the main one, the other just some partial data from the first one. My question is how can I trigger a write into the 2nd firestore instance after an onWrite in the first instance. Is it even feasible?

Here is what's in my cloud function:

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

The rules on the xxx2 side are read/write if true;

However, getting this error on the db1 side:

@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. 

The credentials have been taken from the console.firebase project xxx2 settings. Are they wrong ones? Which ones should I use instead?

1
Sure, it's feasible.Doug Stevenson
Sounds promising. How do I access a different firestore to write into it? Two admin initialisations? If there is an example somewhere would be really helpfulVlad
Asking for examples is off-topic for Stack Overflow, but the documentation for the admin SDK describes how to init the admin SDK to access an arbitrary project. I would suggest starting there, then posting again when you get stuck on something specific.Doug Stevenson
It's unclear from the docs how to retrieve config credentials. The web credentials from the project settings don't seem to work -- see aboveVlad

1 Answers

0
votes

I figured out a solution after trial and error. It is to use a different firebase config from the one above - the private one that is available in the firebase under settings and service accounts - generate private key. Unlike the public one, it should contain your private key etc and you need to keep it only on the backend.

Also, it makes sense to extract the two admin configs into separate files that are loaded into the functions only if/where they are needed:

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