简体   繁体   English

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

[英]Firebase HTTP Cloud Functions - Read database once

I have a Firebase HTTPs function. 我有一个Firebase HTTPs功能。 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数据库中读取值,并根据此数据返回结果。

The Firebase JS SDK says to do this using: Firebase JS SDK说使用以下方法执行此操作:

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('/');

But the DB reference doesn't have the method once , only onWrite ( https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder ). 但是数据库引用没有once方法,只有onWritehttps://firebase.google.com/docs/reference/functions/functions.database.RefBuilder )。 This is obviously for DB write functions, rather than HTTP functions. 这显然适用于DB写入功能,而不是HTTP功能。

Is there a correct way to read from the database once in a HTTP function? 在HTTP函数中有没有正确的方法从数据库中读取一次? Can I use the normal Firebase SDK, or is there a better way? 我可以使用普通的Firebase SDK,还是有更好的方法?

Thanks. 谢谢。

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? 我找到了解决方案,在这里结合答案如何获取参数和Michael Blight到如何从Cloud函数内部运行查询的答案

The answer there also shows what is required to use firebase-admin. 答案还显示了使用firebase-admin所需的内容。

The following works for me when calling my-project.firebaseapp.com/event/123/. 调用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>`
        );
     });
});

You're confusing two parts: 你混淆了两个部分:

  • the firebase-functions module, which contains the logic to trigger based on database calls with functions.database.ref('/path').onWrite() . firebase-functions模块,包含使用functions.database.ref('/path').onWrite()基于数据库调用触发的逻辑。
  • the firebase-admin module, which allows your function to call into the database. firebase-admin模块,它允许您的函数调用数据库。

Since you have a HTTP function, you should trigger as the documentation for HTTP functions shows : 由于您具有HTTP功能,因此您应该触发HTTP功能文档显示

exports.data = functions.https.onRequest((req, res) => {
  // ...
});

Then in your function, you access the database as the documentation for the Admin SDK shows : 然后在您的函数中,您将访问数据库,因为Admin SDK文档显示

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

So in total: 所以总的来说:

exports.date = functions.https.onRequest((req, res) => {
  admin.database().ref('/users/' + userId).once('value').then(function(snapshot) {
    var username = snapshot.val().username;
    res.status(200).send(username);
  });
});

Note that this is a tricky pattern. 请注意,这是一个棘手的模式。 The call to the database happens asynchronously and may take some time to complete. 对数据库的调用是异步发生的,可能需要一些时间才能完成。 While waiting for that, the HTTP function may time out and be terminated by the Google Cloud Functions system. 在等待时,HTTP功能可能超时并被Google Cloud Functions系统终止。 See this section of the documentation . 请参阅文档的此部分

As a general rule I'd recommend using a Firebase Database SDK or its REST API to access the database and not rely on a HTTP function as middleware. 作为一般规则,我建议使用Firebase Database SDK或其REST API来访问数据库,而不是依赖HTTP功能作为中间件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM