1 回答

TA贡献1906条经验 获得超10个赞
确实可以从 Cloud Function 调用 REST API。您需要使用返回 Promises 的 Node.js 库,例如axios。
在您的问题中,您想写哪些特定的 Firestore 文档并不是 100% 清楚,但我假设它将在批量写入中完成。
因此,以下几行应该可以解决问题:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');
admin.initializeApp();
const db = admin.firestore();
exports.resetAppointmentTimes = functions.pubsub
.schedule('30 20 * * *')
.onRun((context) => {
let apiData;
return axios.get('https://yourapiuri...')
.then(response => {
apiData = response.data; //For example, it depends on what the API returns
const appointmentTimesCollectionRef = db.collection('data');
return appointmentTimesCollectionRef.get();
})
.then((querySnapshot) => {
if (querySnapshot.empty) {
return null;
} else {
let batch = db.batch();
querySnapshot.forEach((doc) => {
batch.update(doc.ref, { fieldApiData: apiData});
});
return batch.commit();
}
})
.catch((error) => {
console.log(error);
return null;
});
});
有两点需要注意:
如果您想将 API 结果添加到某些字段值,您需要提供更多关于您的确切需求的详细信息
重要提示:您需要使用“Blaze”定价计划。事实上,免费的“Spark”计划“只允许向 Google 拥有的服务发出出站网络请求”。请参阅https://firebase.google.com/pricing/(将鼠标悬停在“云功能”标题后面的问号上)
添加回答
举报