亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號