Yuri Vaskovski
Yuri Vaskovski

Reputation: 3

Google Cloud Functions req/res with Promise by node-fetch

I am a total newbie to Javascript and trying to set up a bridge between two of the services I use. The goal is simply take body or the request, do a promise api call to another service to respond with the body of that api call. I have been able to take the body of the request and send it to the service, but I'm having trouble receiving that response and making body of that response as a response of the function. Please help me out. Thank you.

var moment = require('moment');
var CryptoJS = require("crypto-js");
const fetch = require('node-fetch');

var unixtime = moment().unix();
var apiUser = process.env.apiUser;
var secret = process.env.apiKey;
var url = process.env.url;

exports.test = (req, res) => {
  var message = req.body;
  message = JSON.stringify(message);
  var body = "{\n    \"ops\": [{\n        \"conv_id\": \"679690\",\n        \"type\": \"create\",\n        \"obj\": \"task\",\n        \"data\": message\n    }]\n}\n"
  body = body.replace(/message/ig, message);
  var signature = CryptoJS.enc.Hex.stringify(CryptoJS.SHA1(unixtime + secret + body + secret));

  function request1() {
    return new Promise((resolve, reject) => {

      var options = fetch(url+apiUser+'/'+unixtime+'/'+signature, {
          method: 'post',
          body: body,
          headers: { 'Content-Type': 'application/json' },
      });

      options.then(res => {
          var result = res.json;
          console.log(result);
          resolve(result);
        })
        .catch(() => { // if .then fails
          console.log('Promise rejected');
          let rejectMessage = 'Sorry, an error occurred.';
          reject(rejectMessage); // Promise rejected
        });
    });
  }

  request1();
};

Upvotes: 0

Views: 137

Answers (1)

Karlo A. López
Karlo A. López

Reputation: 2668

you can retrieve result object easily because function request1 returns a promise resolving that object, so this should work:

request1().then((resultObject)=>{
    //resultObject === result
    return res.send(resultObject);
});

Also, res.json() returns a promise, so you should do:

options.then(res => res.json()).then(result => {
          console.log(result);
          resolve(result);
        })

Upvotes: 2

Related Questions