我在Reactjs中有一个脚本,可以从api获取数据(数字),并在用户打开页面并且用户可以看到此数字时,将这些数字与Firebase集合中的数字相加。 该应用程序中将有许多用户,并且每个用户的同一脚本的号码都不同
我想知道Firebase Cloud Functions是否有可能在服务器上运行此客户端脚本,并在服务器上对该数字进行调用并将其存储在Firestore集合中。
我是nodejs和云函数的入门者,我不知道这样做是否可行
从Api获取号码
getLatestNum = (sym) => {
return API.getMarketBatch(sym).then((data) => {
return data;
});
};
我正在尝试的云功能
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;
});
});
答案 0 :(得分:1)
确实可以从Cloud Function调用REST API。您需要使用一个返回Promises的Node.js库,例如axios。
在您的问题中,尚不清楚要写入哪个特定的Firestore文档,但我不确定它会在批量写入中完成。
因此,以下几行应该可以解决问题:
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;
});
});
注意两点: