diff --git a/dist/wumpfetch.concat.js b/dist/wumpfetch.concat.js index d2c2efe..f6dc6fe 100644 --- a/dist/wumpfetch.concat.js +++ b/dist/wumpfetch.concat.js @@ -1,96 +1,117 @@ -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 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 common = [ 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH' ]; const WumpResponse = class WumpResponse { - constructor ( res ) { - this.body = Buffer.alloc( 0 ); + 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 ]); } + _addChunk (chunk) { + this.body = Buffer.concat([ this.body, chunk ]); + } - text () { return this.body.toString(); } - json () { return JSON.parse( this.body ); } + text () { + return this.body.toString(); + } + + json () { + return JSON.parse(this.body); + } }; - const WumpRequest = class WumpRequest { - constructor ( url = {}, m = {} ) { + 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' ); + 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 : {} + '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 ), + 'rHeaders' : obj && typeof o.headers === 'object' ? o.headers : {}, + 'streamed' : !!( obj && o.streamed ), + 'compressed' : !!( obj && o.compressed ), + '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 ] ) ); + 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 ); + 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 ); + 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; + 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( ', ' ); + 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; } + 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)'; + 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 ); + 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); } } @@ -102,55 +123,55 @@ const WumpRequest = class WumpRequest { 'method' : this.o.m, 'headers' : this.o.rHeaders, 'protocol': this.o.url.protocol - }, this.o.coreOptions ); + }, this.o.coreOptions); - const resHandler = async( res ) => { + 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() ); + 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 ); + if ( this.o.streamed ) resolve(stream); else { - wumpRes = new WumpResponse( res ); + 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 ); + if (res.headers.hasOwnProperty('location') && this.o.follow) { + this.o.url = (new URL(res.headers['location'], this.o.url)).toString(); + return await w(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(); + 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 ); + 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.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, () => { + if (this.o.timeoutTime) { + req.setTimeout(this.o.timeoutTime, () => { req.abort(); - if ( !this.o.streamed ) reject( new Error( 'Timeout reached' ) ); + 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.on('error', (e) => reject(e)); + if (this.o.data) req.write(JSON.stringify(this.o.data)); req.end(); }); @@ -158,8 +179,14 @@ const WumpRequest = class WumpRequest { }; -function createRequest(url, method) { - return new WumpRequest(url, method) +function w(url, method) { + return new WumpRequest(url, method); } -module.exports = createRequest; \ No newline at end of file +module.exports = w; + +common.forEach((v) => { + module.exports[v.toLowerCase()] = (url, method = v) => { + return new WumpRequest(url, method); + } +}); \ No newline at end of file diff --git a/dist/wumpfetch.min.js b/dist/wumpfetch.min.js index cc5f38a..05962d9 100644 --- a/dist/wumpfetch.min.js +++ b/dist/wumpfetch.min.js @@ -1 +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; \ No newline at end of file +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"],common=["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"],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),rHeaders:r&&"object"==typeof o.headers?o.headers:{},streamed:!(!r||!o.streamed),compressed:!(!r||!o.compressed),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 w(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 w(e,t){return new WumpRequest(e,t)}module.exports=w,common.forEach(e=>{module.exports[e.toLowerCase()]=((t,o=e)=>new WumpRequest(t,o))}); \ No newline at end of file diff --git a/test.js b/test.js index f0f9757..3dca1c5 100644 --- a/test.js +++ b/test.js @@ -2,8 +2,6 @@ const u = require('util'); const l = require('lumah'); const w = require('./createRequest.js'); -console.log(w) - l.register('Fetch cat image A', async (end) => { const r = await w({ url: 'https://aws.random.cat/meow', parse: 'json' }).send(); end(r.statusCode === 200 ? true : false, r.statusCode === 200 ? u.inspect(r.body) : r.statusCode);