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

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

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

不负相思意 2023-08-18 14:28:10
这是我想要实现的目标的一个想法。使用云函数,有没有办法在不使用axios的情况下获取API数据?有没有办法在预定的 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;  });本质上,我希望使我的 Firestore 数据库与 Zubie API 保持同步,该 API 每两分钟更新一次车辆位置。或者,我使用 nextJS 并探索使用 useSWR 在页面加载时完成这些更新。然而,这也带来了自身的挑战。
查看完整描述

1 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

使用云函数,有没有办法在不使用axios的情况下获取API数据?

如果您想访问某些 API,则必须自己编写该代码。Cloud Functions 不会为您执行此操作。Cloud Functions 只是一个托管容器,在触发时运行您的代码。

有没有办法在预定的 pubsub 函数中获取这些数据?

当然,您可以编写一个计划函数来定期触发,并且可以让该代码访问 API。那应该不会比你现在遇到的困难。您可以重用几乎所有代码。

本质上,我希望使我的 Firestore 数据库与 Zubie API 保持同步,该 API 每两分钟更新一次车辆位置。

您最多只能每 5 分钟运行一次计划功能。它无法配置为更频繁地运行。


查看完整回答
反对 回复 2023-08-18
  • 1 回答
  • 0 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信