How to access multiple Realtime Database instances in Cloud Functions for Firebase

社会主义新天地 提交于 2019-12-06 01:14:41

问题


I'm using multiple databases in a Firebase project. Cloud functions for the main (default) database work great, however, I cannot make them work for a secondary database. For example I want to make a read request on a node with admin privileges:

//this works
admin.database().ref(nodePath).once('value')...

This works in the main database, however, if I want to execute the command on another database, it doesn't work:

//this doesn't work
admin.database(secondaryDatabaseUrl).ref(nodePath).once('value')...

Although the functions are deployed, I get an error on the console when trying to execute the cloud function.

Here's the code for the cloud function with an https trigger:

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

exports.testFunction= functions.https.onRequest((req, res) => {
  const key = req.query.key;
  // Exit if the keys don't match
  if (!secureCompare(key, functions.config().cron.key)) {
    console.error('keys do not match');
    res.status(403).send('error1');
    return;
  }
  //test read request
  //the line below crashes the function
  return admin.database('https://secondary_db_url.firebaseio.com').ref(`/testNode`).once('value').then(dataSnapshot=> {
    console.log('value', dataSnapshot.val());
    return;
  }).catch(er => {
    console.error('error', er);
    res.status(403).send('error2');
  });
});

Below is the error log in the Firebase console:

TypeError: ns.ensureApp(...).database is not a function
    at FirebaseNamespace.fn (/user_code/node_modules/firebase-admin/lib/firebase-namespace.js:251:42)
    at exports.testFunction.functions.https.onRequest (/user_code/index.js:16:16)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:41)
    at /var/tmp/worker/worker.js:671:7
    at /var/tmp/worker/worker.js:655:9
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)

If I don't specify the secondary database URL, the function will make the read request on my main database which works great:

//this works
return admin.database().ref(`/testNode`).once('value').then(dataSnapshot=> {
...

I'm using the latest SDK versions: "firebase-admin": "^5.5.1" and "firebase-functions": "^0.7.3"

So, how do I get an instance of a secondary database in cloud functions using admin privileges?


回答1:


Here's how to access database by URL using Admin SDK:

let app = admin.app();
let ref = app.database('https://secondary_db_url.firebaseio.com').ref();

Here's an example from Admin SDK integration tests: https://github.com/firebase/firebase-admin-node/blob/master/test/integration/database.js#L52




回答2:


So it looks like you are trying to access multiple databases using the javascript web client API. Passing the URL of the database to the API like this doesn't work with the Admin SDK:

admin.database('https://secondary_db_url.firebaseio.com').ref(`/testNode`)

Instead, you have to initialize a second app, give it a name, and pass that app around to the Admin SDK APIs. Here's a complete sample that writes the same data to two different database instances in the same project:

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

const otherConfig = Object.assign({}, functions.config().firebase)
otherConfig.databaseURL = 'https://your-other-db.firebaseio.com/'
const otherApp = admin.initializeApp(otherConfig, 'otherAppName')

exports.foo = functions.https.onRequest((req, res) => {
    const data = { foo: 'bar' }
    const p1 = admin.database().ref('data').set(data)
    const p2 = admin.database(otherApp).ref('data').set(data)
    Promise.all([p1, p2]).then(() => {
        res.send("OK")
    })
    .catch(error => {
        res.status(500).send(error)
    })
})



回答3:


With cloud functions > 1.1 now, here is the documentation link that saved my life on this issue.

https://firebase.google.com/docs/database/usage/sharding#connect_your_app_to_multiple_database_instances

So, it looks like this at the top of my my cloud function index.js :

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

const dev = admin.initializeApp({
  databaseURL: "https://appdev.firebaseio.com"
}, 'dev');

const v2 = admin.initializeApp({
  databaseURL: "https://appv2.firebaseio.com"
}, 'v2');

and then, in my clond functions functions code I can do :

//will change stuff on default database
admin.database().ref().child(`stuff/${stuffId}`).set(myStuff)

//will change stuff on my dev database
admin.database(dev).ref().child(`stuff/${stuffId}`).set(myStuff)

//will change stuff on my v2 database
admin.database(v2).ref().child(`stuff/${stuffId}`).set(myStuff)



回答4:


So if both the answers doesn't work.

What happened with me is both the method worked without any error but second instance of database was not getting updated.

I updated npm and firebase CLI it worked.

Also @Dough Stevenson you Passing the URL of the database to the API like this **does** work with the Admin SDK

And this is a good blog from Firebase about the same Firebase Blog : Easier scaling with multi-database support!



来源:https://stackoverflow.com/questions/47861381/how-to-access-multiple-realtime-database-instances-in-cloud-functions-for-fireba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!