Add minified version!

This commit is contained in:
Wessel T
2019-02-16 14:59:13 +01:00
parent ae809bf11c
commit 8ee9ec09f0
10 changed files with 297 additions and 80 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
yarn.lock

View File

@@ -69,4 +69,4 @@ const w = require( 'wumpfetch' );
### Why should i use wumpfetch? ### Why should i use wumpfetch?
Wumpfetch is a lightweight and fast request library comparing to other packages such as request and node-fetch which are both around 1.5-4mb in size Wumpfetch is a lightweight and fast request library comparing to other packages such as request and node-fetch which are both around 1.5-4mb in size
[![install size](https://packagephobia.now.sh/badge?p=wumpfetch)](https://packagephobia.now.sh/result?p=wumpfetch) [![install size](https://packagephobia.now.sh/badge?p=wumpfetch)](https://packagephobia.now.sh/result?p=wumpfetch) (6kb concatenated and 3.84kb minified, both in **/dest**)

View File

@@ -1,3 +1,5 @@
const { join } = require('path'); const { join } = require('path');
module.exports = ( url, method ) => { return new( require( join( __dirname, 'model', 'WumpRequest.js' ) ) )( url, method ); }; module.exports = (url, method) => {
return new(require(join( __dirname, 'model', 'WumpRequest.js')))(url, method);
};

165
dist/wumpfetch.concat.js vendored Normal file
View File

@@ -0,0 +1,165 @@
const http = require( 'http' );
const https = require( 'https' );
const { URL } = require( 'url' );
const { join } = require( 'path' );
const { stringify } = require( 'querystring' );
const { createGunzip, createInflate } = require( 'zlib' );
const c = [ 'gzip', 'deflate' ];
const WumpResponse = class WumpResponse {
constructor ( res ) {
this.body = Buffer.alloc( 0 );
this.coreRes = res;
this.headers = res.headers;
this.statusCode = res.statusCode;
}
_addChunk ( chunk ) { this.body = Buffer.concat([ this.body, chunk ]); }
text () { return this.body.toString(); }
json () { return JSON.parse( this.body ); }
};
const WumpRequest = class WumpRequest {
constructor ( url = {}, m = {} ) {
const o = typeof url === 'string' ? m : url;
const obj = typeof o === 'object';
if ( typeof url !== 'string' && !o.hasOwnProperty( 'url' ) ) throw new Error( 'Missing url parameter' );
this.o = {
'm' : typeof o === 'string' ? o : obj && o.method ? o.method : 'GET',
'url' : typeof url === 'string' ? new URL( url ) : obj && typeof o.url === 'string' ? new URL( o.url ) : url,
'SDA' : obj && typeof o.sendDataAs === 'string' ? o.sendDataAs : undefined,
'data' : obj && o.data ? o.data : obj && o.form ? stringify( o.form ) : undefined,
'parse' : obj && o.parse ? o.parse : undefined,
'follow' : !!( obj && o.followRedirects ),
'streamed' : !!( obj && o.streamed ),
'compressed' : !!( obj && o.compressed ),
'rHeaders' : obj && typeof o.headers === 'object' ? o.headers : {},
'timeoutTime' : obj && typeof o.timeout === 'number' ? o.timeout : null,
'coreOptions' : obj && typeof o.coreOptions === 'object' ? o.coreOptions : {}
};
if ( typeof o.core === 'object' ) Object.keys( o.core ).forEach( ( v ) => this.option( v, o.core[ v ] ) );
return this;
}
query ( a, b ) {
if ( typeof a === 'object' ) Object.keys( a ).forEach( ( v ) => this.o.url.searchParams.append( v, a[ v ] ) );
else this.o.url.searchParams.append( a, b );
return this;
}
body ( data, SA ) {
this.o.SDA = typeof data === 'object' && !SA && !Buffer.isBuffer( data ) ? 'json' : ( SA ? SA.toLowerCase() : 'buffer' );
this.o.data = this.SDA === 'form' ? stringify( data ) : ( this.SDA === 'json' ? JSON.stringify( data ) : data );
return this;
}
header ( a, b ) {
if (typeof a === 'object') Object.keys( a ).forEach( ( v ) => this.o.rHeaders[ v.toLowerCase() ] = a[ v ] );
else this.o.rHeaders[ a.toLowerCase() ] = b;
return this;
}
compress () {
this.compressed = true;
if ( !this.o.rHeaders[ 'accept-encoding' ] ) this.o.rHeaders[ 'accept-encoding' ] = c.join( ', ' );
return this;
}
path ( p ) { this.o.url.pathname = join( this.o.url.pathname, p ); return this; }
stream () { this.o.streamed = true; return this; }
option ( n, v ) { this.o.coreOptions[ n ] = v; return this; }
timeout ( timeout ) { this.o.timeoutTime = timeout; return this; }
send () {
return new Promise( ( resolve, reject ) => {
if ( this.o.data ) {
if ( !this.o.rHeaders.hasOwnProperty( 'user-agent' ) ) this.o.rHeaders[ 'User-Agent' ] = 'wumpfetch/0.0.1 (https://github.com/PassTheWessel/wumpfetch)';
if ( this.o.SDA === 'json' && !this.o.rHeaders.hasOwnProperty( 'content-type' ) ) this.o.rHeaders[ 'Content-Type' ] = 'application/json';
if ( this.o.SDA === 'form') {
if ( !this.o.rHeaders.hasOwnProperty( 'content-type' ) ) this.o.rHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
if ( !this.o.rHeaders.hasOwnProperty( 'content-length' ) ) this.o.rHeaders[ 'Content-Length' ] = Buffer.byteLength( this.o.data );
}
}
let req;
const options = Object.assign({
'host' : this.o.url.hostname,
'port' : this.o.url.port,
'path' : this.o.url.pathname + this.o.url.search,
'method' : this.o.m,
'headers' : this.o.rHeaders,
'protocol': this.o.url.protocol
}, this.o.coreOptions );
const resHandler = async( res ) => {
let stream = res;
if ( this.o.compressed ) {
if ( res.headers[ 'content-encoding' ] === 'gzip' ) stream = res.pipe( createGunzip() );
else if ( res.headers[ 'content-encoding' ] === 'deflate' ) stream = res.pipe( createInflate() );
}
let wumpRes;
if ( this.o.streamed ) resolve( stream );
else {
wumpRes = new WumpResponse( res );
if ( res.headers.hasOwnProperty('location') && this.o.follow ) {
this.o.url = ( new URL( res.headers[ 'location' ], this.o.url ) ).toString();
return await createRequest( this.o );
}
stream.on( 'error', ( e ) => reject( e ) );
stream.on( 'data', ( c ) => wumpRes._addChunk( c ) );
stream.on( 'end', () => {
if ( this.o.parse ) {
if ( this.o.parse === 'json' ) wumpRes.body = JSON.parse( wumpRes.body );
else if ( this.o.parse === 'text' ) wumpRes.body = wumpRes.body.toString();
else wumpRes.body = wumpRes.body;
}
resolve( wumpRes );
});
}
};
if ( this.o.url.protocol === 'http:' ) req = http.request( options, resHandler );
else if (this.o.url.protocol === 'https:') req = https.request( options, resHandler );
else throw new Error( `Bad URL protocol: ${this.o.url.protocol}` );
if ( this.o.timeoutTime ) {
req.setTimeout( this.o.timeoutTime, () => {
req.abort();
if ( !this.o.streamed ) reject( new Error( 'Timeout reached' ) );
});
}
req.on( 'error', ( e ) => reject( e ) );
if ( this.o.data ) req.write( JSON.stringify( this.o.data ) );
req.end();
});
}
};
function createRequest(url, method) {
return new WumpRequest(url, method)
}
module.exports = createRequest;

1
dist/wumpfetch.min.js vendored Normal file
View File

@@ -0,0 +1 @@
const http=require("http"),https=require("https"),{URL:URL}=require("url"),{join:join}=require("path"),{stringify:stringify}=require("querystring"),{createGunzip:createGunzip,createInflate:createInflate}=require("zlib"),c=["gzip","deflate"],WumpResponse=class{constructor(e){this.body=Buffer.alloc(0),this.coreRes=e,this.headers=e.headers,this.statusCode=e.statusCode}_addChunk(e){this.body=Buffer.concat([this.body,e])}text(){return this.body.toString()}json(){return JSON.parse(this.body)}},WumpRequest=class{constructor(e={},t={}){const o="string"==typeof e?t:e,r="object"==typeof o;if("string"!=typeof e&&!o.hasOwnProperty("url"))throw new Error("Missing url parameter");return this.o={m:"string"==typeof o?o:r&&o.method?o.method:"GET",url:"string"==typeof e?new URL(e):r&&"string"==typeof o.url?new URL(o.url):e,SDA:r&&"string"==typeof o.sendDataAs?o.sendDataAs:void 0,data:r&&o.data?o.data:r&&o.form?stringify(o.form):void 0,parse:r&&o.parse?o.parse:void 0,follow:!(!r||!o.followRedirects),streamed:!(!r||!o.streamed),compressed:!(!r||!o.compressed),rHeaders:r&&"object"==typeof o.headers?o.headers:{},timeoutTime:r&&"number"==typeof o.timeout?o.timeout:null,coreOptions:r&&"object"==typeof o.coreOptions?o.coreOptions:{}},"object"==typeof o.core&&Object.keys(o.core).forEach(e=>this.option(e,o.core[e])),this}query(e,t){return"object"==typeof e?Object.keys(e).forEach(t=>this.o.url.searchParams.append(t,e[t])):this.o.url.searchParams.append(e,t),this}body(e,t){return this.o.SDA="object"!=typeof e||t||Buffer.isBuffer(e)?t?t.toLowerCase():"buffer":"json",this.o.data="form"===this.SDA?stringify(e):"json"===this.SDA?JSON.stringify(e):e,this}header(e,t){return"object"==typeof e?Object.keys(e).forEach(t=>this.o.rHeaders[t.toLowerCase()]=e[t]):this.o.rHeaders[e.toLowerCase()]=t,this}compress(){return this.compressed=!0,this.o.rHeaders["accept-encoding"]||(this.o.rHeaders["accept-encoding"]=c.join(", ")),this}path(e){return this.o.url.pathname=join(this.o.url.pathname,e),this}stream(){return this.o.streamed=!0,this}option(e,t){return this.o.coreOptions[e]=t,this}timeout(e){return this.o.timeoutTime=e,this}send(){return new Promise((e,t)=>{let o;this.o.data&&(this.o.rHeaders.hasOwnProperty("user-agent")||(this.o.rHeaders["User-Agent"]="wumpfetch/0.0.1 (https://github.com/PassTheWessel/wumpfetch)"),"json"!==this.o.SDA||this.o.rHeaders.hasOwnProperty("content-type")||(this.o.rHeaders["Content-Type"]="application/json"),"form"===this.o.SDA&&(this.o.rHeaders.hasOwnProperty("content-type")||(this.o.rHeaders["Content-Type"]="application/x-www-form-urlencoded"),this.o.rHeaders.hasOwnProperty("content-length")||(this.o.rHeaders["Content-Length"]=Buffer.byteLength(this.o.data))));const r=Object.assign({host:this.o.url.hostname,port:this.o.url.port,path:this.o.url.pathname+this.o.url.search,method:this.o.m,headers:this.o.rHeaders,protocol:this.o.url.protocol},this.o.coreOptions),s=async o=>{let r,s=o;if(this.o.compressed&&("gzip"===o.headers["content-encoding"]?s=o.pipe(createGunzip()):"deflate"===o.headers["content-encoding"]&&(s=o.pipe(createInflate()))),this.o.streamed)e(s);else{if(r=new WumpResponse(o),o.headers.hasOwnProperty("location")&&this.o.follow)return this.o.url=new URL(o.headers.location,this.o.url).toString(),await createRequest(this.o);s.on("error",e=>t(e)),s.on("data",e=>r._addChunk(e)),s.on("end",()=>{this.o.parse&&("json"===this.o.parse?r.body=JSON.parse(r.body):"text"===this.o.parse?r.body=r.body.toString():r.body=r.body),e(r)})}};if("http:"===this.o.url.protocol)o=http.request(r,s);else{if("https:"!==this.o.url.protocol)throw new Error(`Bad URL protocol: ${this.o.url.protocol}`);o=https.request(r,s)}this.o.timeoutTime&&o.setTimeout(this.o.timeoutTime,()=>{o.abort(),this.o.streamed||t(new Error("Timeout reached"))}),o.on("error",e=>t(e)),this.o.data&&o.write(JSON.stringify(this.o.data)),o.end()})}};function createRequest(e,t){return new WumpRequest(e,t)}module.exports=createRequest;

17
gulpfile.js Normal file
View File

@@ -0,0 +1,17 @@
const gulp = require('gulp');
const minify = require('gulp-minify');
const concat = require('gulp-concat');
gulp.task('build:node', () => {
return gulp
.src('dist/wumpfetch.concat.js')
.pipe(minify({ noSource: true, ext: { min: '.min.js' } }))
.pipe(gulp.dest('dist'));
});
gulp.task('concat', () => {
return gulp
.src([ 'createRequest.js', 'model/**/*.js' ])
.pipe(concat('wumpfetch.concat.js'))
.pipe(gulp.dest('./dist'));
});

View File

@@ -64,10 +64,24 @@ module.exports = class WumpRequest {
return this; return this;
} }
path ( p ) { this.o.url.pathname = join( this.o.url.pathname, p ); return this; } path (p) {
stream () { this.o.streamed = true; return this; } this.o.url.pathname = join(this.o.url.pathname, p);
option ( n, v ) { this.o.coreOptions[ n ] = v; return this; } return this;
timeout ( timeout ) { this.o.timeoutTime = timeout; return this; } }
stream () {
this.o.streamed = true;
return this;
}
option (n, v) {
this.o.coreOptions[n] = v;
return this;
}
timeout (timeout) {
this.o.timeoutTime = timeout;
return this;
}
send () { send () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View File

@@ -7,8 +7,15 @@ module.exports = class WumpResponse {
this.statusCode = res.statusCode; this.statusCode = res.statusCode;
} }
_addChunk ( chunk ) { this.body = Buffer.concat([ this.body, chunk ]); } _addChunk (chunk) {
this.body = Buffer.concat([ this.body, chunk ]);
}
text () { return this.body.toString(); } text () {
json () { return JSON.parse( this.body ); } return this.body.toString();
}
json () {
return JSON.parse(this.body);
}
}; };

View File

@@ -5,7 +5,11 @@
"author": "Wessel \"wesselgame\" T <discord@go2it.eu>", "author": "Wessel \"wesselgame\" T <discord@go2it.eu>",
"license": "MIT", "license": "MIT",
"main": "createRequest.js", "main": "createRequest.js",
"files": [ "LICENSE", "createRequest.js", "model/" ], "files": [
"LICENSE",
"createRequest.js",
"model/"
],
"bugs": { "bugs": {
"url": "https://www.github.com/PassTheWessel/wumpfetch/issues" "url": "https://www.github.com/PassTheWessel/wumpfetch/issues"
}, },
@@ -25,5 +29,10 @@
"patch", "patch",
"lightweight" "lightweight"
], ],
"dependencies": {} "dependencies": {},
"devDependencies": {
"gulp": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-minify": "^3.1.0"
}
} }

View File

@@ -1,4 +1,4 @@
const w = require( './createRequest' ); const w = require('./createRequest.js');
;( async() => { ;( async() => {
const r = await w({ url: 'https://aws.random.cat/meow', parse: 'json' }).send(); const r = await w({ url: 'https://aws.random.cat/meow', parse: 'json' }).send();