【发布时间】:2019-03-02 18:01:05
【问题描述】:
我有一个 firebase 数据库,我希望创建一个云函数,在将子节点添加到父节点时触发,它应该调用一个 url,其中包含在父节点中添加的子节点的参数。
将调用的 URL 是托管在 Google App Engine 中的 NodeJS Express 应用程序。
如果可能的话,我该怎么做?
【问题讨论】:
标签: node.js firebase google-cloud-functions
我有一个 firebase 数据库,我希望创建一个云函数,在将子节点添加到父节点时触发,它应该调用一个 url,其中包含在父节点中添加的子节点的参数。
将调用的 URL 是托管在 Google App Engine 中的 NodeJS Express 应用程序。
如果可能的话,我该怎么做?
【问题讨论】:
标签: node.js firebase google-cloud-functions
您可以使用 node.js request 库来执行此操作。
由于在 Cloud Function 内部,您必须在执行异步任务时返回 Promise,因此您需要使用接口包装器来处理请求,例如 request-promise。
您可以按照以下方式做一些事情:
.....
var rp = require('request-promise');
.....
exports.yourCloudFucntion = functions.database.ref('/parent/{childId}')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const createdData = snapshot.val();
var options = {
url: 'https://.......',
method: 'POST',
body: ....
json: true // Automatically stringifies the body to JSON
};
return rp(options);
});
如果您想将参数传递给您正在调用的 HTTP(S) 服务/端点,您可以通过请求的主体来完成,例如:
.....
const createdData = snapshot.val();
var options = {
url: 'https://.......',
method: 'POST',
body: {
some: createdData.someFieldName
},
json: true // Automatically stringifies the body to JSON
};
.....
或者通过一些查询字符串键值对,比如:
.....
const createdData = snapshot.val();
const queryStringObject = {
some: createdData.someFieldName,
another: createdData.anotherFieldName
};
var options = {
url: 'https://.......',
method: 'POST',
qs: queryStringObject
};
.....
【讨论】:
2017-11-11 12:23:11 和值 123847271