How to scope Firebase in nested promise Cloud Func

2019-09-15 11:42发布

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条回答
该账号已被封号
2楼-- · 2019-09-15 12:16

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.js file:

const functions = require('firebase-functions');

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

These lines load the firebase-functions and firebase-admin modules, and initialize an admin app 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.

查看更多
登录 后发表回答