How to get current project in nodejs script?

Viewed 44

In the cmd terminal, I can run firebase projects:list to see the current project selected. How can I get the current project when I run my nodejs script in the same terminal?

I have a list of projects to work on, first I use firebase use to pick a project to work on. Here is the result from firebase projects:list

┌──────────────────────┬──────────────────────┬────────────────┬──────────────────────┐
│ Project Display Name │ Project ID           │ Project Number │ Resource Location ID │
├──────────────────────┼──────────────────────┼────────────────┼──────────────────────┤
│ Canvassing           │ canvassing-xx        │ xx             │ us-west1             │
│ EC1                  │ engage-xx            │ xx             │ us-central           │
├──────────────────────┼──────────────────────┼────────────────┼──────────────────────┤
│ PVBC                 │ pvbc-xx    (current) │ xx             │ us-west1            

In this case, the PVBC is the active project.

In my node project, I have a list of functions that need to push to firebase, something like

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

exports.updateState = functions.pubsub.schedule('every 1 minutes').onRun((context) => {
  return bloc.updateActivityState(firestore);
});

I then use "firebase deploy" to push them to the current project I selected with firebase use.

I also have another set of functions that could do just manipulation from command line, like

var fc = require('../firebase_project1_name/config/firebaseConfig.js');
var firebaseConfig = fc.firebaseConfig;
var app = firebase.initializeApp(firebaseConfig);
var db = firebase.firestore(app);
var colDistrict = db.collection('districts');
...

I put firebase config in file and put them under folder of different project, I need a way to get the current project, like pvbc-xx and replace the firebase_project1_name with the proper name so I can get the config for the current selected project.

Even better, I am thinking if I can get current project info, I don't even need store firebase config in files, I may just get the info current firebase-admin.

1 Answers

You can initialize Admin SDK without parameters like admin.initializeApp() as shown below.

const { initializeApp } = require("firebase-admin/app");

const app = initializeApp()

// In case you need the projectId in your code
console.log(app.options.projectId)

In this case the Admin SDK will use Application Default credentials for the current project (when using the emulators) and also deploy the functions to the same. You don't have to keeping changing the credentials this way.

Related