Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Cloud Function config to access other project db

I need to create a Cloud Function that will access the Firebase DB that is running in another project. If it was accessing the db in the current project, I could use code such as

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

however, what I want is for functions.config().firebase to return the information (and, most importantly, credentials) for the other project. Is there any easy way to do this?

like image 310
Prisoner Avatar asked May 12 '17 14:05

Prisoner


People also ask

How do I deploy Firebase to a different project?

When you first initialize your Firebase Hosting project with firebase init you specify what project you want to deploy your app to. This is your default project. The use command allows you to add another project. Select the project you want to use for a different environment, and then give it an alias.

Can you have multiple Firebase projects?

Many apps need only a single Firebase project and the default set up described in the Get Started guides. Examples of when it can be useful to use multiple Firebase projects include: Setting up your development environment to use different Firebase projects based on build type or target.

Can you use Firebase functions with Realtime Database?

With Cloud Functions, you can handle events in the Firebase Realtime Database with no need to update client code. Cloud Functions lets you run Realtime Database operations with full administrative privileges, and ensures that each change to Realtime Database is processed individually.


1 Answers

functions.config().firebase is a reserved namespace and you won't be able to override it. However, you can do cross-project initialization yourself. Here's how I would do it:

First, download a service account for your other project into your functions directory. Name it <project_id>-sa.json. Next, set up some environment config (app.other_project_id is just an example name, not a requirement):

firebase functions:config:set app.other_project_id="<the_project_id>"

Now in your code, you can initialize the Admin SDK like so:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

if (!functions.config().app || !functions.config().app.other_project_id) {
  throw new Error('Cannot start app without app.other_project_id config.');
}

const FB_PROJECT_ID = functions.config().app.other_project_id;
const SERVICE_ACCOUNT = require(`./${FB_PROJECT_ID}-sa.json`);

admin.initializeApp({
  databaseURL: `https://${FB_PROJECT_ID}.firebaseio.com`,
  credential: admin.credential.cert(SERVICE_ACCOUNT)
});

This will have initialized the Admin SDK for the other project.

like image 52
Michael Bleigh Avatar answered Oct 16 '22 22:10

Michael Bleigh