3

I used Google Apps Script with

var response = UrlFetchApp.fetch(url, params);

to get a response from an api. Sadly its too many request and too many data i need to be handled with Google Apps Script in Drive

My idea was now to switch to Google cloud functions and request but its not working.

const request = require('request');

const headers = {
    "Authorization" : "Basic " + Buffer.from('blabla').toString('base64')
};

const params = {
    "method":"GET",
    "headers":headers
};

exports.getCheckfrontBookings = (req, res) => {
  let url = 'https://fpronline.checkfront.com/api/3.0/item'

  request({url:url, qs:params}, function(err, response, body) {
    if(err) { console.log(err); return; }
    console.log("Get response: " + response.statusCode);
  });
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Tobi
  • 1,702
  • 2
  • 23
  • 42
  • You can not return a value from a callback like that. – Sirko Jan 20 '19 at 09:54
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Sirko Jan 20 '19 at 09:54
  • ok even without the return. the require('request') doesnt work in Google cloud functions? – Tobi Jan 20 '19 at 10:10
  • 1
    What does "doesnt work" mean in detail? Do you see error messages? – Sirko Jan 20 '19 at 10:33
  • Detailed stack trace: Error: Cannot find module 'request' – Tobi Jan 20 '19 at 11:57
  • So it seems not your code is wrong, but the `request` module has not been installed. – Sirko Jan 20 '19 at 12:23

1 Answers1

2

request supports callback interfaces natively but does not return a promise, which is what you must do within a Cloud Function.

You could use request-promise (https://github.com/request/request-promise) and the rp(...) method which "returns a regular Promises/A+ compliant promise" and then do something like:

const rp = require('request-promise');

exports.getCheckfrontBookings = (req, res) => {

  var options = {
    uri: 'https://fpronline.checkfront.com/api/3.0/item',
    headers: {
      Authorization: 'Basic ' + Buffer.from('blabla').toString('base64')
    },
    json: true // Automatically parses the JSON string in the response
  };

  rp(options)
    .then(response => {
      console.log('Get response: ' + response.statusCode);
      res.send('Success');
    })
    .catch(err => {
      // API call failed...
      res.status(500).send('Error': err);
    });
};
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121