Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

minimal-request-promise

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

minimal-request-promise - npm Package Compare versions

Comparing version 1.1.0 to 1.2.0

.travis.yml

93

index.js
/*global module, require, global */
var https = require('https');
module.exports = function (callOptions, PromiseImplementation) {
'use strict';
var Promise = PromiseImplementation || global.Promise;
return new Promise(function (resolve, reject) {
var req = https.request(callOptions);
var https = require('https'),
urlParser = require('url'),
minimalRequestPromise = function (callOptions, PromiseImplementation) {
'use strict';
var Promise = PromiseImplementation || global.Promise;
return new Promise(function (resolve, reject) {
var req = https.request(callOptions);
req.on('response', function (res) {
var dataChunks = [];
res.setEncoding('utf8');
res.on('data', function (chunk) {
dataChunks.push(chunk);
req.on('response', function (res) {
var dataChunks = [];
res.setEncoding('utf8');
res.on('data', function (chunk) {
dataChunks.push(chunk);
});
res.on('end', function () {
var response = {
headers: res.headers,
body: dataChunks.join(''),
statusCode: res.statusCode,
statusMessage: res.statusMessage
};
if (callOptions.resolveErrors || (response.statusCode > 199 && response.statusCode < 400)) {
resolve(response);
} else {
reject(response);
}
});
}).on('error', function (e) {
reject(e);
});
res.on('end', function () {
var response = {
headers: res.headers,
body: dataChunks.join(''),
statusCode: res.statusCode,
statusMessage: res.statusMessage
};
if (callOptions.resolveErrors || (response.statusCode > 199 && response.statusCode < 400)) {
resolve(response);
} else {
reject(response);
}
});
}).on('error', function (e) {
reject(e);
if (callOptions.body) {
req.write(callOptions.body);
}
req.end();
});
if (callOptions.body) {
req.write(callOptions.body);
},
mergeObjects = function (target, properties) {
'use strict';
if (!properties) {
return;
}
req.end();
});
};
Object.keys(properties).forEach(function (key) {
target[key] = properties[key];
});
},
createMethodHelper = function (method) {
'use strict';
return function (url, additionalOptions, PromiseImplementation) {
var Promise = PromiseImplementation || global.Promise;
return Promise.resolve(url)
.then(function (url) {
return urlParser.parse(url);
}).then(function (parsedUrl) {
var options = {};
mergeObjects(options, parsedUrl);
options.method = method;
mergeObjects(options, additionalOptions);
return minimalRequestPromise(options, Promise);
});
};
};
module.exports = minimalRequestPromise;
module.exports.get = createMethodHelper('GET');
module.exports.post = createMethodHelper('POST');
{
"name": "minimal-request-promise",
"version": "1.1.0",
"version": "1.2.0",
"description": "A+ Promise interface to Node.js HTTPS request, with no dependencies",

@@ -25,3 +25,3 @@ "main": "index.js",

"devDependencies": {
"fake-http-request": "^1.2.0",
"fake-http-request": "^1.3.0",
"jasmine": "^2.4.1",

@@ -28,0 +28,0 @@ "jasmine-spec-reporter": "^2.4.0"

#Minimal Promise version of HTTPS request
This is a wrapper for the standard HTTPS Node Request object, that provides an A+ Promise interface to request execution and automates the process of assembling the response body as a string. It can handle posting body contents, and automatically rejects the promise if the response code is not between 200 and 399.
[![Build Status](https://travis-ci.org/gojko/minimal-request-promise.svg?branch=master)](https://travis-ci.org/gojko/minimal-request-promise)
The intent of this library is to wrap requests into a promise interface with minimal overhead, with no dependencies, and just expose the standard Node.js arguments.
This is a wrapper for the standard HTTPS Node Request object, that provides an A+ Promise interface to request execution and automates the process of assembling the response body as a string. It can handle posting body contents, and automatically rejects the promise if the response code is not between 200 and 399.
The intent of this library is to wrap requests into a promise interface with minimal overhead, with no dependencies, and just expose the standard Node.js arguments.
It's not trying to be a fully-featured replacement for complex workflows, streaming etc. For more complex libraries that can provide all kind of workflows like that, see [request-promise](https://github.com/request/request-promise) and [got](https://github.com/sindresorhus/got).
##Installation
Install using NPM:
```bash
npm install minimal-request-promise
```
[![NPM](https://nodei.co/npm/minimal-request-promise.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/minimal-request-promise/)
##Usage

@@ -12,5 +24,7 @@

* `body`: string -- the content to include in the request body when posting
* `resolveErrors`: boolean -- if true, HTTP error response codes will result in a resolved promise (instead of rejected). Only network errors will result in a rejected promise. If false (default), network errors and successful HTTP requests with an error response code will cause the promise to be rejected.
* `body`: `string`, the content to include in the request body when posting
* `resolveErrors`: `boolean`, if true, HTTP error response codes will result in a resolved promise (instead of rejected). Only network errors will result in a rejected promise. If false (default), network errors and successful HTTP requests with an error response code will cause the promise to be rejected.
If you want to execute a FORM POST, remember to add the [`Content-Length` header](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13) as well. This library intentionally does not automatically add that, to keep the interface in line with standard Node.JS requests.
##Example

@@ -40,3 +54,3 @@

console.log('got response', response.body, response.headers);
},
},
function (response) {

@@ -49,2 +63,36 @@ console.log('got error', response.body, response.headers, response.statusCode, response.statusMessage);

##GET and POST method shortcuts
In addition to using the standard Node.js request parameters, you can also generate basic parameters from URLS for GET and POST using the helper methods. The helper methods are `.get` and `.post`, and they expect the following arguments:
* `url`: `string`, a URL to GET or POST to
* `options`: _(optional)_ `object`, key-value map of additional options, described in the [Usage](#usage) section
* `Promise`: _(optional)_ `Function`, an alternate Promise implementation. See [Using with a different Promise library](#using-with-a-different-promise-library).
Example:
```javascript
var requestPromise = require('minimal-request-promise'),
options = {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
recipient: {
id: recipient
},
message: message
})
};
requestPromise.post('https://graph.facebook.com/v2.6/me/messages?access_token=' + fbAccessToken, options).then(
function (response) {
console.log('got response', response.body, response.headers);
},
function (response) {
console.log('got error', response.body, response.headers, response.statusCode, response.statusMessage);
}
);
```
##Using with a different Promise library

@@ -51,0 +99,0 @@

@@ -1,2 +0,2 @@

/*global beforeEach, afterEach, describe, it, expect, require */
/*global beforeEach, afterEach, describe, it, expect, require, jasmine */
var fakeRequest = require('fake-http-request'),

@@ -45,2 +45,78 @@ underTest = require('../index'),

});
['GET', 'POST'].forEach(function (method) {
describe(method + ' helper', function () {
var helper;
beforeEach(function () {
helper = underTest[method.toLowerCase()];
});
it('rejects in case a url is not provided', function () {
helper().catch(function (err) {
expect(err instanceof TypeError).toBeTruthy();
});
});
it('decomposes the URL into params', function (done) {
https.request.pipe(function (args) {
expect(args).toEqual(jasmine.objectContaining({
method: method,
hostname: 'npmjs.org',
path: '/'
}));
done();
});
helper('https://npmjs.org');
});
it('resolves when the underlying request responds', function (done) {
https.request.pipe(function () {
this.respond('200', 'OK', 'Never Program Mad');
});
helper('https://npmjs.org').then(function (response) {
expect(response.statusCode).toEqual('200');
expect(response.statusMessage).toEqual('OK');
expect(response.body).toEqual('Never Program Mad');
}).then(done, done.fail);
});
it('allows options to override method', function (done) {
https.request.pipe(function (args) {
expect(args).toEqual(jasmine.objectContaining({
method: 'ZOOM',
hostname: 'npmjs.org',
path: '/'
}));
done();
});
helper('https://npmjs.org', {method: 'ZOOM'});
});
it('allows options to override URL components', function (done) {
https.request.pipe(function (args) {
expect(args).toEqual(jasmine.objectContaining({
method: method,
hostname: 'npmjs.org',
path: '/bing'
}));
done();
});
helper('https://npmjs.org', {path: '/bing'});
});
it('passes the promise implementation to the request generator', function () {
var FakeImplementation = function () {
var self = this;
self.resolve = function () {
return this;
};
self.then = function () {
return this;
};
self.catch = function () {
return this;
};
},
result;
FakeImplementation.resolve = function () {
return new FakeImplementation();
};
result = helper('https://npmjs.org', {}, FakeImplementation);
expect(FakeImplementation.prototype.isPrototypeOf(result)).toBeTruthy();
});
});
});
});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc