作者:宝贝猪雯 | 来源:互联网 | 2022-11-22 09:05
我是Google Cloud Functions功能和实现的新手。因此,我想知道是否可以使用Cloud函数向第三方服务器API发出HTTP或HTTPS请求,如果可以,怎么办?当我收到响应数据时,可以使用相同的云函数实例将其存储到Firebase数据库中吗?
以及如何使该请求被定期调用或安排?提前致谢
1> Renaud Tarne..:
您可以使用node.js 请求库来做到这一点。
您可以按照以下方式进行操作,例如:
.....
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拥有的服务(例如您提到的“第三方服务器”),则需要采用“火焰”或“大火”的定价方案。
实际上,免费的“ Spark”计划“仅允许对Google拥有的服务的出站网络请求”。请参阅https://firebase.google.com/pricing/(将鼠标悬停在“云函数”标题后面的问号上)
根据您的评论进行更新:
如果要触发对第三方服务器的调用,然后使用从该服务器接收到的数据填充Firebase Realtime数据库,则可以执行以下操作。我以请求请求文档中的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);
});
});