Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to multiple databases in google cloud functions

I want to listen to two databases in my google cloud functions so I tried this

 const app1 = admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "https://honey.firebaseio.com"
});

const app2 = admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "https://honey-d8.firebaseio.com/"
}, 'app2'); 




// Get the default database instance for an app1
var OperationDB = admin.database().ref();

// Get a database instance for app2
var userDB = admin.database(app2).ref();

then I tried to call the second database

 exports.onBoardNewUser = functions.userDB.ref('/Users/').onCreate((snapshot, context) => {

 })

whenever I attempt to deploy the file it gives this error

Cannot read property 'ref' of undefined

The two databases are in the same project

I have tried different variations but no luck. what am I doing wrong an how can I fix this ?

like image 699
e.iluf Avatar asked Feb 02 '26 10:02

e.iluf


1 Answers

You can't attach a Cloud Function to some arbitrary database reference. Cloud Functions database triggers are not like listeners that you get with the client SDKs. It receives events from Realtime Database as they are generated.

You have to use the provided API to build a function that references a particular database and path to receive updates.

You can't reference a database outside of the project where you deployed the function.

You can reference multiple shards of a database within the same project. To do that, you have to specify the name of the shard instance using the provided API. If you don't name the instance in the function builder using the instance() method, you will only receive events from the primary/default shard.

If you want to handle events for all of your shards at the same location in each one, you have to export one function for each shard, and they can each delegate to the same helper function to handle the event.

like image 95
Doug Stevenson Avatar answered Feb 05 '26 05:02

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!