Google Cloud功能可从第三方服务器获取数据 [英] Google Cloud function to fetch data from third party server

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

问题描述

我是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"服务器.或"Blaze"定价计划.

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 Realtime数据库,则可以执行以下操作.我举了一个从请求承诺文档中调用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作业定期调用此Cloud Function,例如 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);
    });
});

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

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