【问题标题】:Google Cloud function to fetch data from third party server谷歌云功能从第三方服务器获取数据
【发布时间】:2019-06-04 06:58:58
【问题描述】:

我是 Google Cloud Functions 功能和实现的新手。所以我想知道是否可以使用云功能向第三方服务器 API 发出 HTTP 或 HTTPS 请求,如果可以,那么如何?当我收到响应数据时,是否可以使用相同的云函数实例将其存储到我的 firebase 数据库中?

我怎样才能使这个请求被定期调用或安排呢?提前致谢

【问题讨论】:

  • @arudzinska 我知道云的功能,它有事件和触发器。但是我不知道我是否可以通过云功能发出HTTP请求。以及如何安排这个 HTTP 请求?
  • 云函数几乎是在托管容器中运行的节点脚本。因此,您可以在 Cloud Functions 中执行大多数可以在节点脚本中执行的操作。如果您想知道:可以在 Cloud Functions 中完成某些事情,我建议您搜索如何在 Node.js 中执行相同的操作,然后尝试在 Cloud Functions 中执行此操作。大多数情况下,如果没有,这将起作用:在用例中发布问题。
  • @FrankvanPuffelen 非常感谢。为我展示了如何在未来搜索与云功能相关的查询的路径。这是一个很大的帮助。

标签: node.js firebase google-cloud-platform google-cloud-functions httprequest


【解决方案1】:

2020 年 5 月 8 日更新

request-promise 现已弃用,我建议使用 axios


您可以使用 node.js request-promise 库来执行此操作。

你可以按照这些思路做一些事情,例如:

.....
var rp = require('request-promise');
.....

exports.yourCloudFunction = functions.database.ref('/parent/{childId}')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const createdData = snapshot.val();

      var options = {
          url: 'https://.......',
          method: 'POST',
          body: ....  
          json: true // Automatically stringifies the body to JSON
      };

      return rp(options);

    });

如果您想将参数传递给您正在调用的 HTTP(S) 服务/端点,您可以通过请求的主体来完成,例如:

  .....
  const createdData = snapshot.val();

  var options = {
      url: 'https://.......',
      method: 'POST',
      body: {
          some: createdData.someFieldName
      },
      json: true // Automatically stringifies the body to JSON
  };
  .....

或者通过一些查询字符串键值对,比如:

  .....
  const createdData = snapshot.val();
  const queryStringObject = { 
     some: createdData.someFieldName,
     another: createdData.anotherFieldName
  };

  var options = {
      url: 'https://.......',
      method: 'POST',
      qs: queryStringObject
  };
  .....

重要提示:

请注意,如果您打算调用非 Google 拥有的服务(例如您提到的“第三方服务器”),则需要使用“Flame”或“Blaze”定价方案。

事实上,免费的“Spark”计划“只允许向 Google 拥有的服务发出出站网络请求”。请参阅https://firebase.google.com/pricing/(将鼠标悬停在“云功能”标题后面的问号上)


根据您的评论更新:

如果您想触发对第三方服务器的调用,然后使用从该服务器接收到的数据填充 Firebase 实时数据库,您可以执行以下操作。我从 request-promise 文档中举了一个调用 API 的例子:https://github.com/request/request-promise#get-something-from-a-json-rest-api

然后,您将定期使用在线 CRON 作业(例如 https://www.easycron.com/)调用此 Cloud Function。

exports.saveCallToAPI = functions.https.onRequest((req, res) => {
  var options = {
    uri: 'https://api.github.com/user/repos',
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true // Automatically parses the JSON string in the response
  };

  rp(options)
    .then(repos => {
      console.log('User has %d repos', repos.length);

      const dbRef = admin.database().ref('userName'); //For example we write to a userName node
      var newItemRef = dbRef.push();
      return newItemRef.set({
        nbrOfRepos: repos.length
      });
    })
    .then(ref => {
      response.send('Success');
    })
    .catch(error => {
      response.status(500).send(error);
    });
});

【讨论】:

  • 感谢您的回答,但我正在寻找相反的方式。我的意思是先发出请求,然后对 firebase 数据库进行更改。
  • 有什么理由让您更喜欢request-promise 而不是axios?谢谢!
  • 嗨@Crashalot。不,实际上现在更喜欢使用 Axios,因为 `request-promise 已被弃用。我会更新答案。
【解决方案2】:

这里是使用node-fetch的方法。

您的云功能:

const fetch = require('node-fetch');

exports.functionName= (req, res) => {
  const fetchFromURL = async () => await (await fetch('https://yourURL.com')).json();

  fetchFromURL().then((data) => {
    // do something with data (received from URL).
  });
};

您还需要将“node-fetch”依赖项添加到函数的 package.json 中。

你的 package.json:

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "node-fetch": "^2.6.1"
  }
}

【讨论】:

  • import fetch from 'node-fetch'
猜你喜欢
  • 2021-05-06
  • 2018-09-22
  • 2019-05-15
  • 2019-06-05
  • 1970-01-01
  • 2017-11-14
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多