简体   繁体   English

使用 Firebase Cloud Functions,我可以从外部 API 安排更新以更新 Firestore

[英]Using Firebase Cloud Functions, can I schedule updates from an external API to update Firestore

Here is an idea of what I'm trying to accomplish.这是我要完成的工作的一个想法。 Using cloud functions, is there a way to fetch API data without axios?使用云函数,有没有办法在没有axios的情况下获取API数据? Is there a way to get this data inside a scheduled pubsub function?有没有办法在预定的 pubsub 函数中获取这些数据?

const functions = require('firebase-functions');
const axios = require('axios');
const cors = require('cors')({ origin: true });


exports.getVehicles = functions.https.onCall((req:any, res:any) => {
  cors(req, res, () => {
    if (req.method !== "GET") {
      return res.status(401).json({
        message: "Not allowed"
      });
    }
    return axios.get('https://api.zubiecar.com/api/v2/zinc/vehicles', {
              method: 'GET', // or 'PUT'
              headers: {
                'Content-Type': 'application/json',
                "Zubie-Api-Key": "123456789"
         },
     })
        .then((response:any) => {
          console.log(response.data);
          return res.status(200).json({
            message: response.data.ip
          })
        })
        .catch((err:any) => {
          return res.status(500).json({
            error: err
          })
        })
  
    })
  });


  exports.updateDriverLocation = functions.pubsub.schedule('every 2 minutes').onRun(async(context:any) => {
    
    //return array of driver objects from api
    const update = await getVehicles();

    //database
    const DB = admin.firestore()
    const REF = DB.collection("drivers")
    const BATCH = DB.batch()  
    
    //update firestore with api response
    update.forEach((vehicle:any) => {
        BATCH.set( REF.doc(vehicle.nickname),
          {vehicle},
          { merge: true }
        )
    })
    await BATCH.commit()
    return null;
  });

Essentially, I'm looking to keep my Firestore database in sync with the Zubie API, which updates vehicle locations every two minutes.从本质上讲,我希望我的 Firestore 数据库与 Zubie API 保持同步,它每两分钟更新一次车辆位置。 Alternatively, I am using nextJS and exploring the use of useSWR to accomplish these updates when a page loads.或者,我正在使用 nextJS 并探索使用 useSWR 在页面加载时完成这些更新。 However, that is presenting its own challenges also.然而,这也带来了自己的挑战。

ANSWER回答

const getVehicles = async () => {
  let url = `https://api.zubiecar.com/api/v2/zinc/vehicles`
  let response = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Zubie-Api-Key':'fooBar',
    },
  })
  const json = await response.json()
  return json
}

exports.updateVehicles = functions.pubsub
  .schedule('every 5 minutes')
  .onRun(async () => {
    const DB = admin.firestore()
    const REF = DB.collection('drivers')
    const BATCH = DB.batch()
    const {vehicles} = await getVehicles()
    for (const key in vehicles) {
      const vehicle = vehicles[key]
      const {nickname} = vehicle
      BATCH.set(REF.doc(nickname), {vehicle}, {merge: true})
    }
    await BATCH.commit()
    return
  })

Using cloud functions, is there a way to fetch API data without axios?使用云函数,有没有办法在没有axios的情况下获取API数据?

If you want to access some API, you'll have to write that code yourself.如果您想访问某些 API,则必须自己编写该代码。 Cloud Functions will not do that for you. Cloud Functions 不会为您执行此操作。 Cloud Functions is just a hosted container that runs your code when triggered. Cloud Functions 只是一个托管容器,可在触发时运行您的代码。

Is there a way to get this data inside a scheduled pubsub function?有没有办法在预定的 pubsub 函数中获取这些数据?

Sure, you can write a scheduled function to trigger periodically, and you can have that code access the API.当然,您可以编写一个计划函数来定期触发,并且您可以让该代码访问 API。 That should be no more difficult than what you have now.这应该不会比你现在拥有的更困难。 You can reuse almost all the code.您可以重用几乎所有代码。

Essentially, I'm looking to keep my Firestore database in sync with the Zubie API, which updates vehicle locations every two minutes.从本质上讲,我希望我的 Firestore 数据库与 Zubie API 保持同步,它每两分钟更新一次车辆位置。

You can only run scheduled functions at most every 5 minutes.您最多只能每 5 分钟运行一次预定功能。 It can't be configured to run more frequently.它无法配置为更频繁地运行。

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

相关问题 如何使用 Cloud Functions 计划对我的 Firebase Firestore 数据库中的集合进行批量更新? - How do I schedule a batch update to a collection in my Firebase Firestore database using Cloud Functions? 我无法从Firebase Firestore中的Firebase云功能写入数据 - I can not write data from the Firebase Cloud Functions in Firebase Firestore 使用 Cloud Functions 从 Firestore 数据库上的外部 API 存储数据 - Using Cloud Functions to store data form an external API on Firestore database 与 firebase 云函数中的 firebase firestore 交互 - Interacting with firebase firestore from firebase cloud functions 使用 Firestore 中的 Firebase 云函数推送通知 - Push Notifications Using Firebase Cloud Functions in Firestore Firebase云功能/ Firestore - Firebase Cloud Functions / Firestore 在云功能中更新Firestore - Update firestore in cloud functions 如何在功能区中从Firestore获取用户的电子邮件? - how can I get the email of the user from firestore in cloud functions? 是否可以从 firebase 云函数 node.js 更新 firestore 中类型映射的字段? - Is it possible to update a field of type map in firestore from firebase cloud functions node.js? 如何使用 Firebase 云功能更新 Firestore 文档的值 - How to update value of a firestore document with a firebase cloud functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM