Firebase 云函数调用客户端脚本



我在 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;
});
});

确实可以从云函数调用 REST API。你需要使用一个返回 Promise 的 Node.js 库,比如 axios。

在您的问题中,并不是 100% 清楚您要写入哪个特定的 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;
});
});

需要注意两件事:

  1. 如果要将 API 结果添加到某些字段值,则需要提供有关确切需求的更多详细信息
  2. 重要提示:您需要使用"Blaze"定价计划。事实上,免费的"Spark"计划">只允许对谷歌拥有的服务发出出站网络请求"。请参阅 https://firebase.google.com/pricing/(将鼠标悬停在"云功能"标题后面的问号上(

相关内容

最新更新