繁体   English   中英

Firebase 云 function 调用客户端脚本

[英]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;
        });
});

有两点需要注意:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM