Google Cloud function to fetch data from third party server

前端 未结 2 1742
梦毁少年i
梦毁少年i 2021-01-05 09:16

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 fun

2条回答
  •  臣服心动
    2021-01-05 09:39

    UPDATE on 8 May 2020

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


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

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

    IMPORTANT:

    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.

    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)


    UPDATE FOLLOWING YOUR COMMENT:

    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.

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

提交回复
热议问题