Firebase HTTP云功能 - 一次读取数据库

时间:2017-05-11 10:43:33

标签: javascript firebase firebase-realtime-database google-cloud-functions

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

Firebase JS SDK说使用以下方法执行此操作:

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

但是,云功能示例包含:

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

functions.database.ref('/');

但是数据库引用没有方法once,只有onWritehttps://firebase.google.com/docs/reference/functions/functions.database.RefBuilder)。这显然适用于DB编写函数,而不是HTTP函数。

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

感谢。

1 个答案:

答案 0 :(得分:36)

我找到了解决方案,在这里结合答案如何获得参数和Michael Blight的回答 How to run query from inside of Cloud function?

答案还显示了使用firebase-admin所需的内容。

以下内容适用于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>`
        );
     });
});