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/(將鼠標懸停在“云功能”標題后面的問號上)
添加回答
舉報