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;

      });

  });


慕森卡
浏览 87回答 1
1回答

隔江千里

确实可以从 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/(将鼠标悬停在“云功能”标题后面的问号上)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript