如何从云函数内部运行查询?
Posted
技术标签:
【中文标题】如何从云函数内部运行查询?【英文标题】:How to run query from inside of Cloud function? 【发布时间】:2017-08-09 15:57:07 【问题描述】:一旦调用了我的 Firebase 应用上的云函数,我想对我的数据库执行查询。
假设我在数据库上有某个触发器,考虑get started guide on Firebase中提供的示例。
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/pushId/original')
.onWrite(event =>
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
console.log('Uppercasing', event.params.pushId, original);
const uppercase = original.toUpperCase();
// I'D LIKE TO PERFORM A QUERY HERE, JUST A SIMPLE RETRIEVE BASED ON THE ID PROVIDED
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
);
我应该导入哪些模块(如果有的话)? 如何在 DB 上执行查询?
提前感谢您的回答!
【问题讨论】:
【参考方案1】:您可以为此使用Node.js Admin SDK:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.makeUppercase = functions.database()
.ref('/messages/pushId/original')
.onWrite(event =>
return admin.database().ref('/other')
.orderByChild('id').equalTo(event.params.pushId)
.once('value').then(snapshot =>
// there, I queried!
);
);
【讨论】:
不太工作....我试过这个.. admin.database().ref('chats/g1/push-key-1').toJSON().valueOf('id' ) ...但它似乎没有返回值。 这是database().
而不是database.
以上是关于如何从云函数内部运行查询?的主要内容,如果未能解决你的问题,请参考以下文章