[英]Unable to call Firebase Cloud Function from client-side with fetch
[英]Firebase cloud function call client side script
我在 Reactjs 中有一個腳本,它從 api 獲取數據(數字)並將這些數字與來自 Firebase 的數字相加,當用戶打開頁面時,用戶可以看到這個數字集合。 應用程序中會有很多用戶,每個用戶都會有來自同一個腳本的不同數字
我想知道是否可以使用 Firebase Cloud Functions 在服務器上運行此客戶端腳本並在服務器上計算此號碼並將此號碼存儲在 Firestore 集合中。
我是 nodejs 和雲功能的初學者我不知道這是否可行
從 Api 獲取數字
getLatestNum = (sym) => {
return API.getMarketBatch(sym).then((data) => {
return data;
});
};
雲 function 我正在嘗試
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.resetAppointmentTimes = functions.pubsub
.schedule('30 20 * * *')
.onRun((context) => {
const appointmentTimesCollectionRef = db.collection('data');
return appointmentTimesCollectionRef
.get()
.then((querySnapshot) => {
if (querySnapshot.empty) {
return null;
} else {
let batch = db.batch();
querySnapshot.forEach((doc) => {
console.log(doc);
});
return batch.commit();
}
})
.catch((error) => {
console.log(error);
return null;
});
});
確實可以從雲 Function 調用 REST API。 您需要使用返回 Promise 的 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;
});
});
有兩點需要注意:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.