问题
I am trying to set a few variables from Firebase and then pass those into a anotherfunction. Currently, the Promise.all is properly setting foo and bar, but an error is being thrown during the .then, so the response isn't getting set in Firebase.
const functions = require('firebase-functions'),
admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.someFunc = functions.database.ref(`/data`).onWrite(event => {
const condition = event.data.val()
if (condition) {
// Get the data at this location only once, returns a promise, to ensure retrieval of foo and bar
const foo = event.data.adminRef.child('foo').once('value')
const bar = event.data.adminRef.child('bar').once('value')
return Promise.all([foo, bar]).then(results => {
const foo = results[0].val()
const bar = results[1].val()
return someModule.anotherFunction({
"foo": foo,
"bar": bar
}).then(response => {
// Get an error thrown that Firebase is not defined
let updates = {}
updates['/data'] = response
return firebase.database().ref().update(updates)
})
})
} else {
console.log('Fail')
}
});
The error logged into the console is as follows:
ReferenceError: firebase is not defined
at someModule.anotherFunction.then.response
(/user_code/index.js:100:16)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
How can return firebase.database().ref().update(updates); be scoped to set the response from anotherFunction?
回答1:
You need to include the Firebase Admin SDK, typically called admin.
As shown and explained in the getting started documentation for functions:
Import the required modules and initialize
For this sample, your project must import the Cloud Functions and Admin SDK modules using Node require statements. Add lines like the following to your
index.jsfile:const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase);These lines load the
firebase-functionsandfirebase-adminmodules, and initialize anadminapp instance from which Realtime Database changes can be made.
You then use it like this:
return admin.database().ref().update(updates);
Also see this complete example in the functions-samples repo.
来源:https://stackoverflow.com/questions/43960390/how-to-scope-firebase-in-nested-promise-cloud-functions