firebasefirebase-realtime-databasegoogle-cloud-functionsenvironment

Deploy a Cloud Function to different Firebase projects


I have two firebase projects, one for development (project-dev) and one for production (project-prod).

I initialized firebase CLI for writing and deploying cloud functions linked to project-prod. Then I ran firebase use --add and added project-dev so that I can deploy the same function to both projects; I don't want to rewrite the same function twice.

At this point, I faced the problem. Into the function, I have to write something to the realtime database, but when I deploy the function to project-dev it writes to project-prod's database.

What I want to achieve is that the function has to refer to the database of the project that it is deployed to. So that I have one function and when it is deployed to project-dev it writes to project-dev's database and when it is deployed to project-prod it writes to project-prod's database.

Is it possible to achieve that? If not, what's the way to go?

EDIT

Function code:

exports.AddOrders= functions.https.onRequest(async (req, res) => {
    async function addOrder(key, value) {
        var ref = app.database().ref("/orders");
        return ref.child(key).set(value);
    }

    var orders = req.body['orders'];
    var promises = [];
    for (var key in orders) {
        promises.push(addOrder(key, orders[key]));
    }
    Promise.all(promises).then(
        _ => {
            res.sendStatus(200);
            return null;
        }
    ).catch(err => {
        res.send(err);
    })
});

(This function works fine, the problem is that it writes on the wrong database)


Solution

  • This is the answer for anyone wondering what the problem was.

    He was initialising the admin sdk with the credentials of a service account tied to the production project. The solution was to change it to admin.initializeApp() without passing any arguments. This made Firebase use the default credentials for each project.

    I know its a common mistake but again, here is the link to the corresponding documentation https://firebase.google.com/docs/admin/setup