谷歌云函数从第三方服务器获取数据 [英] Google Cloud function to fetch data from third party server

查看:23
本文介绍了谷歌云函数从第三方服务器获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Google Cloud Functions features and implementation. So I want to know that is it possible to make HTTP or HTTPS request to third party server API using Cloud function and if yes then how? And when I receive data in response can I store it into my firebase database using same cloud function instance?

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

And how can I make this request to be called periodically or schedule it? Thanks in advance

推荐答案

2020 年 5 月 8 日更新

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

UPDATE on 8 May 2020

request-promise being now deprecated, I recommend to use axios.

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

You can use the node.js request-promise library to do so.

您可以按照这些方式做一些事情,例如:

You could do something along these lines, for example:

.....
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) 服务/端点,您可以通过请求的正文来完成,例如:


If you want to pass parameters to the HTTP(S) service/endpoint you are calling, you can do it through the body of the request, like:

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

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

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

or through some query string key-value pairs, like:

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

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


重要提示:

请注意,如果您计划调用非 Google 拥有的服务(如您提到的第三方服务器"),则您需要处于Flame"状态.或火焰"定价计划.

Note that if you plan to call a non Google-owned service (like the "third party server" you mentioned), you need to be on the "Flame" or "Blaze" pricing plan.

事实上,免费的Spark"计划仅允许对 Google 拥有的服务的出站网络请求".请参阅 https://firebase.google.com/pricing/(将鼠标悬停在位于在云功能"标题之后)

As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)

根据您的评论进行更新:

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

If you want to trigger a call to the third party server and then populate the Firebase Realtime Database with data received from this server you could do as follows. I took an example of call to an API from the request-promise documentation: https://github.com/request/request-promise#get-something-from-a-json-rest-api.

然后,您将使用在线 CRON 作业定期调用此云函数,例如 https://www.easycron.com/.

You would then call this Cloud Function regularly with an online CRON job like https://www.easycron.com/.

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

这篇关于谷歌云函数从第三方服务器获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆