New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

oohttp

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

oohttp - npm Package Compare versions

Comparing version 0.3.1 to 1.0.0

136

index.js

@@ -42,3 +42,3 @@ 'use strict';

this.protocol = null;
this.auth = null;
// this.auth = null;
this.hostname = null;

@@ -196,5 +196,7 @@ this.port = null;

/*
if (!this.auth && baseUrl.auth) {
this.auth = baseUrl.auth;
}
*/

@@ -260,5 +262,7 @@ if (!this.hostname && baseUrl.hostname) {

/*
if (this.auth) {
str += `${this.auth}@`;
}
*/

@@ -317,2 +321,12 @@ // hostname

class Response {
constructor(obj) {
if (obj) {
this.data = obj.data;
this.headers = obj.headers;
this.statusCode = obj.statusCode;
}
}
}
class Request {

@@ -333,2 +347,22 @@ constructor(method, reqUrl) {

static get(reqUrl) {
return new Request('GET', reqUrl);
}
static post(reqUrl) {
return new Request('POST', reqUrl);
}
static put(reqUrl) {
return new Request('PUT', reqUrl);
}
static delete(reqUrl) {
return new Request('DELETE', reqUrl);
}
static patch(reqUrl) {
return new Request('PATCH', reqUrl);
}
/**

@@ -347,3 +381,3 @@ * Parses the result through JSON and passes it to the given constructor.

return this.send(data)
.then(res => new Constr(JSON.parse(res)))
.then(res => new Constr(JSON.parse(res.data)))
.catch((err) => {

@@ -360,3 +394,3 @@ if (err.statusCode === 404) {

.then((res) => {
const json = JSON.parse(res);
const json = JSON.parse(res.data);
const arr = [];

@@ -376,3 +410,3 @@

.then((res) => {
const json = JSON.parse(res);
const json = JSON.parse(res.data);
const map = {};

@@ -391,3 +425,3 @@

return this.send(data)
.then(res => `${res}`);
.then(res => `${res.data}`);
}

@@ -397,3 +431,3 @@

return this.send(data)
.then(res => JSON.parse(res));
.then(res => JSON.parse(res.data));
}

@@ -426,8 +460,17 @@

req.onload = () => {
const resHeaders = Request.parseXmlHttpRequestHeaders(req);
if (req.status >= 200 && req.status < 300) {
resolve(req.responseText);
resolve(new Response({
statusCode: req.status,
headers: resHeaders,
data: req.responseText
}));
} else {
const err = new Error('Unsuccessful statuscode returned');
err.statusCode = req.status;
err.data = req.responseText;
err.res = new Response({
statusCode: req.status,
headers: resHeaders,
data: req.responseText
});
reject(err);

@@ -441,5 +484,26 @@ }

/* istanbul ignore next */
static parseXmlHttpRequestHeaders(req) {
const headerMap = {};
const headerStr = req.getAllResponseHeaders();
if (!headerStr) {
return headerMap;
}
const headerSplit = headerStr.split('\r\n');
for (let i = 0; i < headerSplit.length; i += 1) {
const colonIndex = headerSplit.indexOf(':');
if (colonIndex > -1) {
headerMap[headerSplit[i].substring(0, colonIndex)] = headerSplit[i].substring(colonIndex);
}
}
return headerMap;
}
sendNode(data) {
return new Promise((resolve, reject) => {
const options = url.parse(this.url.toString());
const urlStr = this.url.toString();
const options = url.parse(urlStr);
options.method = this.method || Request.defaults.method;

@@ -456,3 +520,3 @@

const protocolName = options.protocol.substring(0, options.protocol.length - 1).toLowerCase();
let protocolName = options.protocol.substring(0, options.protocol.length - 1).toLowerCase();
if (protocolName !== 'http' && protocolName !== 'https') {

@@ -462,3 +526,13 @@ throw new Error(`unsupported protocol "${protocolName}"`);

const req = (protocolName === 'https' ? https : http).request(options, (res) => {
let proxyOptions;
if (this.proxyUrl) {
proxyOptions = url.parse(this.proxyUrl);
proxyOptions.headers = options.headers;
proxyOptions.headers.Host = options.host;
proxyOptions.headers.path = urlStr;
protocolName = 'http';
}
const req = (protocolName === 'https' ? https : http).request(proxyOptions || options, (res) => {
res.setEncoding('utf8');

@@ -472,7 +546,15 @@ let resData = '';

if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(resData);
resolve(new Response({
statusCode: res.statusCode,
headers: res.headers,
data: resData
}));
} else {
const err = new Error('Unsuccessful statuscode returned');
err.statusCode = res.statusCode;
err.data = resData;
err.res = new Response({
statusCode: res.statusCode,
headers: res.headers,
data: resData
});
reject(err);

@@ -502,2 +584,7 @@ }

proxy(proxyUrl) {
this.proxyUrl = proxyUrl;
return this;
}
send(data) {

@@ -531,2 +618,4 @@ if (data && typeof data !== 'string') {

}
/* istanbul ignore next */
return this.sendBrowser(data);

@@ -589,5 +678,26 @@ }

}
get(reqUrl) {
return this.request('GET', reqUrl);
}
post(reqUrl) {
return this.request('POST', reqUrl);
}
put(reqUrl) {
return this.request('PUT', reqUrl);
}
delete(reqUrl) {
return this.request('DELETE', reqUrl);
}
patch(reqUrl) {
return this.request('PATCH', reqUrl);
}
}
module.exports = {
Response,
Request,

@@ -594,0 +704,0 @@ Base,

5

package.json
{
"name": "oohttp",
"version": "0.3.1",
"version": "1.0.0",
"description": "object-oriented http(s) request handler",

@@ -33,4 +33,3 @@ "license": "MIT",

"express": "*",
"body-parser": "*",
"supertest": "*",
"http-proxy": "*",
"mocha": "*",

@@ -37,0 +36,0 @@ "nyc": "*"

@@ -14,6 +14,8 @@ # Description

## Simple request
<pre><code>const oohttp = require('oohttp');
## Simple GET request
```javascript
const oohttp = require('oohttp');
new oohttp.Request('GET', 'http://someurl')
// new oohttp.Request('GET', 'http://someurl')
oohttp.Request.get('http://someurl')
.toJson() // or toString() for the string result

@@ -23,7 +25,32 @@ .then((jsonObj) => {

});
</code></pre>
```
## Posting data
```javascript
const oohttp = require('oohttp');
// new oohttp.Request('POST', 'http://someurl')
oohttp.Request.post('http://someurl')
.toJson({
data: 'somedata'
}) // or toString() for the string result
.then((jsonObj) => {
console.log(jsonObj);
});
```
## Behind a proxy
```javascript
oohttp.Request.get('http://someurl')
.proxy('http://myproxy.intranet')
.toJson()
.then((jsonObj) => {
console.log(jsonObj);
});
```
## Basing
Will request http://someurl?other=value&token=x with the given 'someHeader' header from the base and the [default headers](#Defaults).
<pre><code>const oohttp = require('oohttp');
Will request http://someurl?other=value&token=x with the given `someHeader` header from this base in addition to the [default headers](#Defaults).
```javascript
const oohttp = require('oohttp');

@@ -33,3 +60,4 @@ const base = new oohttp.Base('?token=x');

base.request('http://someurl?other=value')
// base.request('GET', 'http://someurl?other=value')
base.get('http://someurl?other=value')
.toJson()

@@ -39,8 +67,9 @@ .then((jsonObj) => {

});
</pre></code>
```
## Error handling
<pre><code>const oohttp = require('oohttp');
```javascript
const oohttp = require('oohttp');
new oohttp.Request('GET', 'http://nonexistanturl')
oohttp.Request.get('http://nonexistanturl')
.toJson()

@@ -52,9 +81,16 @@ .then((jsonObj) => {

console.log(err.message);
console.log(err.statusCode);
console.log(err.data);
/**
* Log the response object which contains;
* statusCode
* headers
* data
*/
console.log(err.res);
});
</code></pre>
```
## Constructing objects
<pre><code>const oohttp = require('oohttp');
```javascript
const oohttp = require('oohttp');

@@ -69,3 +105,3 @@ class SomeClass {

new oohttp.Request('GET', 'http://someurl/api/objects/someobject')
oohttp.Request.get('http://someurl/api/objects/someobject')
.toObject(SomeClass)

@@ -75,6 +111,7 @@ .then((someObj) => {

});
</code></pre>
```
## Constructing object arrays
<pre><code>const oohttp = require('oohttp');
```javascript
const oohttp = require('oohttp');

@@ -89,3 +126,3 @@ class SomeClass {

new oohttp.Request('GET', 'http://someurl/api/objects')
oohttp.Request.get('http://someurl/api/objects')
.toObjectArray(SomeClass)

@@ -95,3 +132,3 @@ .then((someObjArray) => {

});
</code></pre>
```

@@ -103,3 +140,4 @@ # Defaults

<pre><code>Request.defaults = {
```javascript
Request.defaults = {
headers: {

@@ -112,2 +150,3 @@ 'content-type': 'application/json'

autoContentLength: false
};</code></pre>
};
```

@@ -9,3 +9,2 @@ 'use strict';

const expressApp = require('express')();
const http = require('http');

@@ -30,2 +29,3 @@ const testObject = {

describe('Base', function () {
let base = new oohttp.Base('http://localhost');
before(function () {

@@ -39,7 +39,23 @@ expressServer = expressApp.listen(9800);

describe('passing object as argument', function() {
const newBase = new oohttp.Base({
url: 'http://127.0.0.1/',
autoContentLength: true
});
it('should assign properties', function() {
assert.equal(newBase.autoContentLength, true);
assert(newBase.url instanceof oohttp.Url);
assert.equal(newBase.url.toString(), 'http://127.0.0.1/');
});
});
describe('request()', function () {
const base = new oohttp.Base('http://localhost');
const req = base.request('GET', ':9800/testObject');
it('should return an object', async function () {
it('should return a Request object', async function () {
assert(req instanceof oohttp.Request);
});
it('toObject(constr) should return an object', async function () {
const obj = await req.toObject(Obj);

@@ -49,2 +65,75 @@ assert.deepEqual(testObject, obj);

});
describe('http methods', function () {
describe('get()', function () {
const req = base.get(':9800/testObject');
it('should return a Request object', async function () {
assert(req instanceof oohttp.Request);
});
it('method should be set to GET', async function () {
assert.equal(req.method, 'GET');
});
});
describe('post()', function () {
const req = base.post(':9800/testObject');
it('should return a Request object', async function () {
assert(req instanceof oohttp.Request);
});
it('method should be set to POST', async function () {
assert.equal(req.method, 'POST');
});
});
describe('put()', function () {
const req = base.put(':9800/testObject');
it('should return a Request object', async function () {
assert(req instanceof oohttp.Request);
});
it('method should be set to PUT', async function () {
assert.equal(req.method, 'PUT');
});
});
describe('delete()', function () {
const req = base.delete(':9800/testObject');
it('should return a Request object', async function () {
assert(req instanceof oohttp.Request);
});
it('method should be set to DELETE', async function () {
assert.equal(req.method, 'DELETE');
});
});
describe('patch()', function () {
const req = base.patch(':9800/testObject');
it('should return a Request object', async function () {
assert(req instanceof oohttp.Request);
});
it('method should be set to PATCH', async function () {
assert.equal(req.method, 'PATCH');
});
});
});
describe('base.url = str', function() {
base.url = 'http://127.0.0.1';
it('should be parsed as Url when Request object is created', function() {
const req = base.get('/something');
assert(req.url instanceof oohttp.Url);
assert.equal(req.url.toString(), 'http://127.0.0.1/something');
});
});
});

@@ -76,4 +76,4 @@ 'use strict';

describe('.parse("str")', function () {
const url = new oohttp.Url('https://test.test.test/test?woot=meuq&blaat=woot#strHash');
describe('.parse("str?#")', function () {
const url = new oohttp.Url('https://test.test.test/test?woot=meuq&blaat=woot&woot=meuq2&woot=meuq3#strHash');

@@ -85,3 +85,3 @@ it('should have pathname', function () {

it('should have query', function () {
assert.deepStrictEqual(url.query, { woot: 'meuq', blaat: 'woot' });
assert.deepStrictEqual(url.query, { woot: ['meuq', 'meuq2', 'meuq3'], blaat: 'woot' });
});

@@ -102,40 +102,85 @@

it('toString should be correct', function () {
assert.strictEqual(url.toString(), 'https://test.test.test/test?woot=meuq&blaat=woot#strHash');
assert.strictEqual(url.toString(), 'https://test.test.test/test?woot=meuq&woot=meuq2&woot=meuq3&blaat=woot#strHash');
});
});
describe('merge(Url)', function () {
const baseUrl = new oohttp.Url('https://test.test.test:1234/test?woot=meuq&blaat=woot#strHash');
const url = new oohttp.Url('http:///pathname');
url.mergeFrom(baseUrl);
describe('.parse("str")', function () {
const url = new oohttp.Url('http://test.test.test');
it('should keep protocol', function () {
assert.strictEqual(url.protocol, 'http');
it('should not have pathname', function () {
assert.equal(url.pathname, null);
});
it('should keep pathname', function () {
assert.strictEqual(url.pathname, '/pathname');
it('should have hostname', function () {
assert.strictEqual(url.hostname, 'test.test.test');
});
it('should copy hostname', function () {
assert.strictEqual(url.hostname, 'test.test.test');
it('should have protocol', function () {
assert.strictEqual(url.protocol, 'http');
});
it('should copy port', function () {
assert.strictEqual(url.port, 1234);
it('should not have querystring', function () {
assert.deepStrictEqual(url.query, {});
});
it('toString should be correct', function () {
assert.strictEqual(url.toString(), 'http://test.test.test:1234/pathname?woot=meuq&blaat=woot#strHash');
it('should not have hash', function () {
assert.strictEqual(url.hash, null);
});
});
describe('merge("url")', function () {
const url = new oohttp.Url('https://:1234/pathname?query=str&test=test2');
url.mergeFrom('http://test.test.test?query=string');
describe('.parseQueryString(undefined)', function() {
it('should not parse no querystring', function () {
assert.deepStrictEqual(oohttp.Url.parseQueryString(), {});
});
});
it('toString should be correct', function () {
assert.strictEqual(url.toString(), 'https://test.test.test:1234/pathname?query=str&query=string&test=test2');
describe('merge', function () {
describe('mergeFrom(Url)', function () {
const baseUrl = new oohttp.Url('https://test.test.test:1234/test?woot=meuq&blaat=woot#strHash');
const url = new oohttp.Url('http:///pathname');
url.mergeFrom(baseUrl);
it('should keep protocol', function () {
assert.strictEqual(url.protocol, 'http');
});
it('should keep pathname', function () {
assert.strictEqual(url.pathname, '/pathname');
});
it('should copy hostname', function () {
assert.strictEqual(url.hostname, 'test.test.test');
});
it('should copy port', function () {
assert.strictEqual(url.port, 1234);
});
it('toString should be correct', function () {
assert.strictEqual(url.toString(), 'http://test.test.test:1234/pathname?woot=meuq&blaat=woot#strHash');
});
});
describe('mergeFrom("url")', function () {
it('toString should be correct', function () {
const url = new oohttp.Url('https://:1234/pathname?query=str&test=test2');
url.mergeFrom('http://test.test.test?query=string');
assert.strictEqual(url.toString(), 'https://test.test.test:1234/pathname?query=str&query=string&test=test2');
});
it('toString should be correct', function () {
const url = new oohttp.Url('https://:1234?query=str&test=test2');
url.mergeFrom('http://test.test.test/pathname?query=string');
assert.strictEqual(url.toString(), 'https://test.test.test:1234/pathname?query=str&query=string&test=test2');
});
});
describe('mergeFrom(null)', function () {
const url = new oohttp.Url('https://test');
url.mergeFrom();
it('should not do anything', function () {
assert.strictEqual(url.toString(), 'https://test');
});
});
});
});

@@ -8,6 +8,13 @@ 'use strict';

const oohttp = require('../index.js');
const expressApp = require('express')();
expressApp.use(require('body-parser').json());
const http = require('http');
const express = require('express');
const httpProxy = require('http-proxy');
const expressApp = express();
expressApp.use(express.json());
expressApp.get('/testSend', (req, res) => {
res.setHeader('test-header', 'true');
res.send('some-data');
});
const testArray = [

@@ -57,2 +64,25 @@ {

expressApp.get('/testTimeout', (req, res) => {
setTimeout(() => {
res.end();
}, 2000);
});
// express for urlencoded post bodies
const expressUrlEncodedApp = express();
expressUrlEncodedApp.use(express.urlencoded());
expressUrlEncodedApp.post('/testPostBody', (req, res) => {
res.json(req.body);
});
// proxy
const proxyServer = httpProxy.createProxyServer();
const proxyWebserver = require('http').createServer((req, res) => {
res.setHeader('proxy-test', 'true');
proxyServer.web(req, res, {
target: req.headers.path
});
});
// test object

@@ -66,2 +96,3 @@ class Obj {

let expressServer;
let expressUrlEncodedAppServer;

@@ -71,2 +102,4 @@ describe('Request', function () {

expressServer = expressApp.listen(9800);
expressUrlEncodedAppServer = expressUrlEncodedApp.listen(9801);
proxyWebserver.listen(9802);
});

@@ -76,4 +109,23 @@

expressServer.close();
expressUrlEncodedAppServer.close();
proxyServer.close();
proxyWebserver.close();
});
describe('send()', function () {
let res;
before(async function () {
const req = new oohttp.Request('GET', 'http://localhost:9800/testSend');
res = await req.send();
});
it('should have headers', function () {
assert.equal(res.headers['test-header'], 'true');
});
it('should have data', function () {
assert.equal(res.data, 'some-data');
});
});
describe('toObjectArray()', function () {

@@ -84,3 +136,3 @@ let objs;

objs = await req.toObjectArray(Obj);
})
});

@@ -111,5 +163,13 @@ it('should return a list of Obj instances', async function () {

it('should contain error', async function () {
assert(thrownErr.res instanceof oohttp.Response);
});
it('should return statusCode 404', async function () {
assert.strictEqual(thrownErr.statusCode, 404);
})
});
it('statusCode on error should equal response statusCode', async function () {
assert.strictEqual(thrownErr.statusCode, thrownErr.res.statusCode);
});
});

@@ -123,3 +183,3 @@

});
it('should return a map of Obj instances', async function () {

@@ -156,3 +216,3 @@ Object.keys(objs).forEach(key => assert(objs[key] instanceof Obj));

try {
obj = await req.toObject(testStr);
await req.toObject(testStr);
} catch (err) {

@@ -217,2 +277,10 @@ thrownErr = err;

});
it('non-numbers and non-strings should be deleted', async function () {
req.headers['x-test-header'] = 'test';
req.headers['x-obj-header'] = { some: 'obj' };
const headers = await req.toJson();
assert.strictEqual(headers['x-test-header'], 'test');
assert.strictEqual(headers['x-obj-header'], undefined);
});
});

@@ -231,2 +299,119 @@

});
describe('auto content length', function () {
const req = new oohttp.Request('POST', 'http://localhost:9800/testPostBody');
req.autoContentLength = true;
it('should set content-length header', async function () {
const postBody = {
test: 'value'
};
await req.toJson(postBody);
assert.equal(req.headers['content-length'], 16);
});
});
describe('non json content-type', function () {
const req = new oohttp.Request('POST', 'http://localhost:9801/testPostBody');
req.headers['content-type'] = 'application/x-www-form-urlencoded';
it('should encode form data', async function () {
const postBody = {
test: 'value',
test2: 'value2',
escaped: 'some&thing?etc'
};
const returnBody = await req.toJson(postBody);
assert.deepEqual(postBody, returnBody);
});
});
describe('timeouts', function () {
const req = new oohttp.Request('GET', 'http://localhost:9800/testTimeout');
req.timeout = 1000;
it('should trigger timeout event', async function () {
let thrownErr;
try {
await req.send();
} catch (err) {
thrownErr = err;
}
assert(thrownErr instanceof Error);
assert.equal(thrownErr.message, 'timeout');
});
});
describe('http methods', function () {
describe('get()', function () {
it('method should be set to GET', function () {
const req = oohttp.Request.get('someurl');
assert.equal(req.method, 'GET');
});
});
describe('post()', function () {
it('method should be set to POST', function () {
const req = oohttp.Request.post('someurl');
assert.equal(req.method, 'POST');
});
});
describe('put()', function () {
it('method should be set to PUT', function () {
const req = oohttp.Request.put('someurl');
assert.equal(req.method, 'PUT');
});
});
describe('delete()', function () {
it('method should be set to DELETE', function () {
const req = oohttp.Request.delete('someurl');
assert.equal(req.method, 'DELETE');
});
});
describe('patch()', function () {
it('method should be set to PATCH', function () {
const req = oohttp.Request.patch('someurl');
assert.equal(req.method, 'PATCH');
});
});
});
describe('proxy', function () {
describe('req.proxyUrl', function() {
let res;
before(async function () {
const req = oohttp.Request.get('http://localhost:9800/testObject');
req.proxyUrl = 'http://localhost:9802';
res = await req.send();
});
it('should have proxy header', function () {
assert.equal(res.headers['proxy-test'], 'true');
});
});
describe('req.proxy()', function() {
let req;
before(function () {
req = oohttp.Request.get('http://localhost:9800/testObject');
});
it('should chain', function() {
assert.equal(req.proxy('http://localhost:9802'), req);
});
it('should set proxyUrl', function() {
assert.equal(req.proxyUrl, 'http://localhost:9802');
});
it('should have proxy header', async function () {
const res = await req.send();
assert.equal(res.headers['proxy-test'], 'true');
});
});
});
});
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