【问题标题】:How to scope Firebase in nested promise Cloud Functions如何在嵌套的 Promise Cloud Functions 中定义 Firebase
【发布时间】:2017-05-14 04:30:11
【问题描述】:

我正在尝试从 Firebase 设置一些变量,然后将它们传递给另一个函数。目前,Promise.all 正在正确设置 foo 和 bar,但在 .then 期间抛出错误,因此未在 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')
  }
});

登录到控制台的错误如下:

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)

如何限定return firebase.database().ref().update(updates); 以设置来自anotherFunction 的响应?

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions


    【解决方案1】:

    您需要include the Firebase Admin SDK,通常称为admin

    getting started documentation for functions中所示和解释:

    导入需要的模块并初始化

    对于此示例,您的项目必须使用 Node 的 require 语句导入 Cloud Functions 和 Admin SDK 模块。在您的 index.js 文件中添加如下行:

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

    这些行加载firebase-functionsfirebase-admin 模块,并初始化一个admin 应用实例,从中可以进行实时数据库更改。

    然后你像这样使用它:

    return admin.database().ref().update(updates);
    

    另见complete example in the functions-samples repo

    【讨论】:

    • 弗兰克,感谢您周到而及时的回复。我确实基于 GitHub 上发布的 Firebase functions-samples 这个函数。我应该对示例更加详细,并在问题中包含常量和初始化。我现在已经用初始化和记录到控制台的错误更新了代码。
    • 你还在打电话给firebase.database().ref().update(updates)。正如我的回答所说,那应该是admin.database().ref().update(updates)
    • 啊,好的。我错过了。
    猜你喜欢
    • 2020-04-22
    • 1970-01-01
    • 2018-10-11
    • 2021-01-09
    • 2018-04-18
    • 1970-01-01
    • 2018-06-29
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多