2020 年 5 月 8 日更新
request-promise 现已弃用,我建议使用 axios。
您可以使用 node.js request-promise 库来执行此操作。
你可以按照这些思路做一些事情,例如:
.....
var rp = require('request-promise');
.....
exports.yourCloudFunction = 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
};
.....
重要提示:
请注意,如果您打算调用非 Google 拥有的服务(例如您提到的“第三方服务器”),则需要使用“Flame”或“Blaze”定价方案。
事实上,免费的“Spark”计划“只允许向 Google 拥有的服务发出出站网络请求”。请参阅https://firebase.google.com/pricing/(将鼠标悬停在“云功能”标题后面的问号上)
根据您的评论更新:
如果您想触发对第三方服务器的调用,然后使用从该服务器接收到的数据填充 Firebase 实时数据库,您可以执行以下操作。我从 request-promise 文档中举了一个调用 API 的例子:https://github.com/request/request-promise#get-something-from-a-json-rest-api。
然后,您将定期使用在线 CRON 作业(例如 https://www.easycron.com/)调用此 Cloud Function。
exports.saveCallToAPI = functions.https.onRequest((req, res) => {
var options = {
uri: 'https://api.github.com/user/repos',
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(repos => {
console.log('User has %d repos', repos.length);
const dbRef = admin.database().ref('userName'); //For example we write to a userName node
var newItemRef = dbRef.push();
return newItemRef.set({
nbrOfRepos: repos.length
});
})
.then(ref => {
response.send('Success');
})
.catch(error => {
response.status(500).send(error);
});
});