Firebase云功能调用客户端脚本

时间:2020-06-28 19:53:43

标签: javascript node.js reactjs firebase google-cloud-functions

我在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 个答案:

答案 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;
        });
});

注意两点:

  1. 如果要将API结果添加到某些字段值中,则需要提供更多有关您实际需要的详细信息
  2. 重要:您需要加入“ Blaze”定价计划。实际上,免费的“ Spark”计划“允许仅对Google拥有的服务的出站网络请求”。请参见https://firebase.google.com/pricing/(将鼠标悬停在“云函数”标题之后的问号上)