Node JS – REST calls with ES6 Promises + Co JS Module

Here is an example of factory that creates an httpService to communicate with an external API with REST. We are using the npm module “request” to perform the HTTP calls. We are using as well ECMAScript 6 classes and promises, as long as the npm module “co”, that allows us to take advantage on the ES6 generators to await for async elaborations that returns a promise.

https://www.npmjs.com/package/co

"use strict";

var request = require("request-promise");
var co = require("co");

class HttpService {
     constructor(baseUri) {
          this.baseUri = baseUri;
          Object.seal(this);
     }

     call(options) {
          var self = this;

          console.log("Calling", self.baseUri + options.uri + "..");

          return new Promise(function (resolve, reject) {
               co(function* () {
                    try {
                         var data = yield request({
                              uri: self.baseUri + options.uri,
                              method: options.method,
                              headers: options.headers,
                              form: options.postData,
                              json: true
                         });
                         console.log(data);
                         resolve(data);
                    } catch (err) {
                         if (err.name == "StatusCodeError") {
                              console.log("ERROR: returned status code was", err.message);
                              reject(err.statusCode);
                         } else {
                              console.log("ERROR:", err.message);
                              reject(500);
                         }
                    }
               });
          });
     }
}

module.exports = {
     make: function (baseUri) {
          return new HttpService(baseUri);
     }
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s