我有 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
, only onWrite
(https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder)。这显然是针对 DB 写入功能,而不是 HTTP 功能。
是否有在 HTTP 函数中从数据库读取一次的正确方法?我可以使用普通的 Firebase SDK,还是有更好的方法?
Thanks.
我找到了解决方案,将此处关于如何获取参数的答案与 Michael Blight 的答案结合起来如何从云函数内部运行查询? https://stackoverflow.com/a/42869266/4982158
那里的答案还显示了使用 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>`
);
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)