为了账号安全,请及时绑定邮箱和手机立即绑定

Firebase 云函数调用客户端脚本

Firebase 云函数调用客户端脚本

慕森卡 2022-10-21 09:34:47
我在 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;      });  });
查看完整描述

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;

        });

});

有两点需要注意:

  1. 如果您想将 API 结果添加到某些字段值,您需要提供更多关于您的确切需求的详细信息

  2. 重要提示:您需要使用“Blaze”定价计划。事实上,免费的“Spark”计划“只允许向 Google 拥有的服务发出出站网络请求”。请参阅https://firebase.google.com/pricing/(将鼠标悬停在“云功能”标题后面的问号上)


查看完整回答
反对 回复 2022-10-21
  • 1 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号