Firebase HTTP Cloud Functions - 读取数据库一次 [英] Firebase HTTP Cloud Functions - Read database once

查看:29
本文介绍了Firebase HTTP Cloud Functions - 读取数据库一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Firebase HTTPs 功能.该函数需要根据查询参数从 Firebase 数据库中读取一个值,并根据该数据返回结果.

I have a Firebase HTTPs function. The function needs to read a value from a Firebase database based on the query parameter, and return a result based on this data.

Firebase JS SDK 说要使用:

The Firebase JS SDK says to do this using:

return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
  var username = snapshot.val().username;
  // ...
});

但是,云函数示例具有:

However, the Cloud functions examples have:

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

functions.database.ref('/');

但是数据库引用没有方法once,只有onWrite (https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder).这显然是针对 DB 写函数,而不是 HTTP 函数.

But the DB reference doesn't have the method once, only onWrite (https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder). This is obviously for DB write functions, rather than HTTP functions.

在 HTTP 函数中是否有正确的方法从数据库中读取一次?我可以使用普通的 Firebase SDK,还是有更好的方法?

Is there a correct way to read from the database once in a HTTP function? Can I use the normal Firebase SDK, or is there a better way?

谢谢.

推荐答案

我找到了解决方案,结合此处关于如何获取参数的答案和 Michael Blight 的答案如何从 Cloud 函数内部运行查询?

I found the solution in combining the answer here on how to get the parameter and an answer from Michael Blight to How to run query from inside of Cloud function?

那里的答案还显示了使用 firebase-admin 的要求.

The answer there also shows what is required to use firebase-admin.

以下在调用 my-project.firebaseapp.com/event/123/时对我有用.

The following works for me when calling my-project.firebaseapp.com/event/123/.

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

admin.initializeApp(functions.config().firebase);

exports.showEvent = functions.https.onRequest((req, res) => {
    const params = req.url.split("/");
    const eventId = params[2];
    return admin.database().ref('events/' + eventId).once('value', (snapshot) => {
        var event = snapshot.val();
        res.send(`
            <!doctype html>
            <html>
                <head>
                    <title>${event.name}</title>
                </head>
                <body>
                    <h1>Title ${event. name} in ${event.city}</h1>
                </body>
            </html>`
        );
     });
});

这篇关于Firebase HTTP Cloud Functions - 读取数据库一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆