从 Firebase 函数访问实时数据库

Vik*_*Vik 3 firebase firebase-realtime-database google-cloud-functions

我们正在为我们的移动应用程序使用 firebase 函数和 firebase 实时数据库。当有人下订单时,我们确实会发送电子邮件,该订单是使用如下 Firebase 数据库触发器实现的:

exports.on_order_received = functions.database.ref("/orders/{id}")
    .onCreate((change, context) => {
        console.log("start of on_order_received")   
...
Run Code Online (Sandbox Code Playgroud)

以上触发器对我们来说很好用。现在,我们有一些要求,图片中没有 DB 触发器。这是一个像下面这样的http请求

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase
Run Code Online (Sandbox Code Playgroud)

问题是我们如何在这里访问实时数据库对象?或者换句话说,我如何获得对 /orders 节点的访问权限?我试过如下

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase
    var ref = functions.database.ref('orders')
    ref.orderByValue().limitToLast(3).on("value", function(snapshot) {
        snapshot.forEach(function(data) {
          console.log("The " + data.key + " dinosaur's score is " + data.val());
        });
    })
Run Code Online (Sandbox Code Playgroud)

但这不起作用。我收到错误“orderByValue() 不是函数”

Dou*_*son 9

您应该使用Firebase Admin SDK。它具有读取和写入数据库的能力。事实上,当您编写数据库触发器时,它提供给您使用的引用实际上来自 Admin SDK,因此它是相同的 API。使用 HTTP 类型函数时只需要自己初始化即可:

// at the top of the file:
const admin = require('firebase-admin');
admin.initializeApp();

// in your function:
const root = admin.database().ref();
// root is now a Reference to the root of your database.
Run Code Online (Sandbox Code Playgroud)


小智 5

您必须使用 theadmin而不是 thefunctions来访问database()读取数据。

(请确保您可以访问firebase-adminsdk,根据您使用的是 TypeScript 还是 JavaScript ,使用importrequire适当的)

// The Firebase Admin SDK to access the Firebase Realtime Database.    
import * as admin from 'firebase-admin';
Run Code Online (Sandbox Code Playgroud)

或者

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
Run Code Online (Sandbox Code Playgroud)

尝试这个:

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase
    /* Do not use functions */ 
    // var ref = functions.database.ref('orders')
    /* Instead use the admin */
    var ref = admin.database().ref('orders')
    ref.orderByValue().limitToLast(3).on("value", function(snapshot) {
        snapshot.forEach(function(data) {
          console.log("The " + data.key + " dinosaur's score is " + data.val());
        });
    })
Run Code Online (Sandbox Code Playgroud)

orderByValue()未定义functions.database- 但实际上可用admin.database().ref()