1.0.0 • Published 3 years ago

newquest v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

newquest

Promisified HTTP requests with bluebird and request modules.

Grab it

$ npm install newquest

newquest usage

GET example

With this wrapper, we can easily make requests and catch any http failures in a promise's catch. By default, method is GET:

var newquest = require('newquest');

newquest('http://localhost:4567/api').then(function (body) {
  console.log('Success!');
}).catch(function (err) { // Any HTTP status >= 400 falls here
  console.error('Failed.', err.statusCode, ' >= 400');
});

If you need the full response (e.g. to view headers), specify arrayResponse: true to have the response and body in an array. You may use bluebird's spread to access the items directly:

newquest({
  url: 'http://localhost:4567/api',
  arrayResponse: true
}).spread(function (response, body) {
  console.log('Success!', response.headers, body);
});

POST example

All options supported by request can be supplied to newquest. By default, json: true is enabled to set body payload as a JSON representation. If you do not want this, simply override it to false.

var newquest = require('newquest');

newquest({
  method: 'POST',
  url: 'http://localhost:4567/api',
  body: {
    someData: [1, 2, 3]
  }
}).then(function (body) {
  console.log('Success!',  body);
}).catch(function (err) { // Any HTTP status >= 400 falls here
  console.error('Failed.', err.statusCode, ' >= 400');
});

To use the other methods: delete, patch, head, specify it in method.

Testing

To run the tests:

$ npm install
$ npm test

The past, without newquest

Without this wrapper, a common pattern to promisify requests:

var Promise = require('bluebird');
var newquest = Promise.promisify(require('request'));

newquest(url).then(function (response) {
  if (reponse.statusCode === 200) {
    // continue;
  } else if (reponse.statusCode >= 500) {
    // handle this error case
  } else if (reponse.statusCode >= 400) {
    // you get the point...
  }
}).catch(function (err) {
  console.error(err);
  // network issue
})