Comparing version 0.4.0 to 0.5.0
@@ -1,1 +0,1 @@ | ||
((a,b)=>{"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?module.exports=b():a.xf=b()})(this,()=>{function a(b,c){const d=a=>a&&"object"==typeof a;return d(b)&&d(c)?(Object.keys(c).forEach(e=>{const f=b[e],g=c[e];b[e]=Array.isArray(f)&&Array.isArray(g)?f.concat(g):d(f)&&d(g)?a(Object.assign({},f),g):g}),b):c}const b=["get","post","put","patch","delete","head"];class c extends Error{constructor(a){super(a.statusText),this.name="HTTPError",this.response=a}}class d extends Promise{}for(const a of["arrayBuffer","blob","formData","json","text"])d.prototype[a]=function(b){return this.then(b=>b[a]()).then(b||(a=>a))};const{assign:e}=Object,f=a=>a.reduce((a,[b,c])=>(a[b]=c,a),{}),g=(...a)=>b=>a.some(a=>"string"==typeof a?typeof b==a:b instanceof a),h=g("string"),i=g("object"),j=a=>h(a)||i(a),k=a=>{if(!a.ok)throw new c(a);return a},l=(i={})=>{const m=(b,c={})=>{a(c,i);const l=a=>new c.URLSearchParams(a).toString(),m=new c.URL(b,c.baseURI||void 0);if(c.headers?g(c.Headers)(c.headers)&&(c.headers=f([...c.headers.entries()])):c.headers={},c.json)c.body=JSON.stringify(c.json),c.headers["Content-Type"]="application/json";else if(j(c.urlencoded))c.body=h(c.urlencoded)?c.urlencoded:l(c.urlencoded),c.headers["Content-Type"]="application/x-www-form-urlencoded";else if(g(c.FormData,"object")(c.formData)){if(!g(c.FormData)(c.formData)){const a=new c.FormData;for(const[b,d]of Object.entries(c.formData))a.append(b,d);c.formData=a}c.body=c.formData}return c.qs&&(h(c.qs)&&(c.qs=(a=>f([...new c.URLSearchParams(a).entries()]))(c.qs)),m.search=l(e(f([...m.searchParams.entries()]),c.qs))),c.credentials||(c.credentials="same-origin"),d.resolve(c.fetch(m,c).then(k))};for(const a of b)m[a]=(b,c={})=>(c.method=a.toUpperCase(),m(b,c));return m.extend=a=>l(e({},i,a)),m.HTTPError=c,m},m="undefined"!=typeof document,n="undefined"!=typeof self;return n?l({fetch:fetch.bind(self),URL,Response,URLSearchParams,Headers,FormData,baseURI:m?document.baseURI:""}):l()}); | ||
((a,b)=>{"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?module.exports=b():a.xf=b()})(this,()=>{function a(b,c){const d=a=>a&&"object"==typeof a;return d(b)&&d(c)?(Object.keys(c).forEach(e=>{const f=b[e],g=c[e];b[e]=Array.isArray(f)&&Array.isArray(g)?f.concat(g):d(f)&&d(g)?a(Object.assign({},f),g):g}),b):c}const b=["get","post","put","patch","delete","head"];class c extends Error{constructor(a){super(a.statusText),this.name="HTTPError",this.response=a}}class d extends Promise{}for(const a of["arrayBuffer","blob","formData","json","text"])d.prototype[a]=function(b){return this.then(b=>b[a]()).then(b||(a=>a))};const{assign:e}=Object,f=a=>a.reduce((a,[b,c])=>(a[b]=c,a),{}),g=(...a)=>b=>a.some(a=>"string"==typeof a?typeof b==a:b instanceof a),h=g("string"),i=g("object"),j=g("undefined"),k=a=>h(a)||i(a),l=a=>{if(!a.ok)throw new c(a);return a},m="content-type",n=a=>{for(const b of Object.keys(a)){const c=b.toLowerCase();b!=c&&(a[c]=a[b],delete a[b])}},o=(i={})=>{const p=(b,c={})=>{a(c,i);const o=a=>new c.URLSearchParams(a).toString(),p=new c.URL(b,c.baseURI||void 0);if(c.headers?g(c.Headers)(c.headers)&&(c.headers=f([...c.headers.entries()])):c.headers={},n(c.headers),c.json)c.body=JSON.stringify(c.json),j(c.headers[m])&&(c.headers[m]="application/json");else if(k(c.urlencoded))c.body=h(c.urlencoded)?c.urlencoded:o(c.urlencoded),j(c.headers[m])&&(c.headers[m]="application/x-www-form-urlencoded");else if(g(c.FormData,"object")(c.formData)){if(!g(c.FormData)(c.formData)){const a=new c.FormData;for(const[b,d]of Object.entries(c.formData))a.append(b,d);c.formData=a}c.body=c.formData}return c.qs&&(h(c.qs)&&(c.qs=(a=>f([...new c.URLSearchParams(a).entries()]))(c.qs)),p.search=o(e(f([...p.searchParams.entries()]),c.qs))),c.credentials||(c.credentials="same-origin"),d.resolve(c.fetch(p,c).then(l))};for(const a of b)p[a]=(b,c={})=>(c.method=a.toUpperCase(),p(b,c));return p.extend=a=>o(e({},i,a)),p.HTTPError=c,p},p="undefined"!=typeof document,q="undefined"!=typeof self;return q?o({fetch:fetch.bind(self),URL,Response,URLSearchParams,Headers,FormData,baseURI:p?document.baseURI:""}):o()}); |
# Example: GitHub avatar fetcher | ||
[https://rawgit.com/maple3142/xfetch-js/master/examples/ghavatar/index.html](https://rawgit.com/maple3142/xfetch-js/master/examples/ghavatar/index.html) | ||
[https://gh.maple3142.net/maple3142/xfetch-js/master/examples/ghavatar/index.html](https://gh.maple3142.net/maple3142/xfetch-js/master/examples/ghavatar/index.html) |
{ | ||
"name": "xfetch-js", | ||
"version": "0.4.0", | ||
"version": "0.5.0", | ||
"description": "", | ||
@@ -5,0 +5,0 @@ "main": "src/node.js", |
@@ -25,3 +25,3 @@ /* | ||
// alias for .json() .text() etc... | ||
XResponsePromise.prototype[alias] = function(fn) { | ||
XResponsePromise.prototype[alias] = function (fn) { | ||
return this.then(res => res[alias]()).then(fn || (x => x)) | ||
@@ -45,3 +45,6 @@ } | ||
} else if (isObject(targetValue) && isObject(sourceValue)) { | ||
target[key] = mergeDeep(Object.assign({}, targetValue), sourceValue) | ||
target[key] = mergeDeep( | ||
Object.assign({}, targetValue), | ||
sourceValue | ||
) | ||
} else { | ||
@@ -54,7 +57,11 @@ target[key] = sourceValue | ||
} | ||
const fromEntries = ent => ent.reduce((acc, [k, v]) => ((acc[k] = v), acc), {}) | ||
const fromEntries = ent => | ||
ent.reduce((acc, [k, v]) => ((acc[k] = v), acc), {}) | ||
const typeis = (...types) => val => | ||
types.some(type => (typeof type === 'string' ? typeof val === type : val instanceof type)) | ||
types.some(type => | ||
typeof type === 'string' ? typeof val === type : val instanceof type | ||
) | ||
const isstr = typeis('string') | ||
const isobj = typeis('object') | ||
const isundef = typeis('undefined') | ||
const isstrorobj = v => isstr(v) || isobj(v) | ||
@@ -65,7 +72,19 @@ const responseErrorThrower = res => { | ||
} | ||
const contentType = 'content-type' | ||
const keysToLowerCase = obj => { | ||
for (const k of Object.keys(obj)) { | ||
const klc = k.toLowerCase() | ||
if (k != klc) { | ||
obj[klc] = obj[k] | ||
delete obj[k] | ||
} | ||
} | ||
} | ||
const extend = (defaultInit = {}) => { | ||
const xfetch = (input, init = {}) => { | ||
mergeDeep(init, defaultInit) | ||
const createQueryString = o => new init.URLSearchParams(o).toString() | ||
const parseQueryString = s => fromEntries([...new init.URLSearchParams(s).entries()]) | ||
const createQueryString = o => | ||
new init.URLSearchParams(o).toString() | ||
const parseQueryString = s => | ||
fromEntries([...new init.URLSearchParams(s).entries()]) | ||
const url = new init.URL(input, init.baseURI || undefined) | ||
@@ -78,9 +97,17 @@ if (!init.headers) { | ||
} | ||
keysToLowerCase(init.headers) // headers is case insensitive | ||
// Add json or form on body | ||
if (init.json) { | ||
init.body = JSON.stringify(init.json) | ||
init.headers['Content-Type'] = 'application/json' | ||
if (isundef(init.headers[contentType])) { | ||
init.headers[contentType] = 'application/json' | ||
} | ||
} else if (isstrorobj(init.urlencoded)) { | ||
init.body = isstr(init.urlencoded) ? init.urlencoded : createQueryString(init.urlencoded) | ||
init.headers['Content-Type'] = 'application/x-www-form-urlencoded' | ||
init.body = isstr(init.urlencoded) | ||
? init.urlencoded | ||
: createQueryString(init.urlencoded) | ||
if (isundef(init.headers[contentType])) { | ||
init.headers[contentType] = | ||
'application/x-www-form-urlencoded' | ||
} | ||
} else if (typeis(init.FormData, 'object')(init.formData)) { | ||
@@ -100,3 +127,8 @@ // init.formData is data passed by user, init.FormData is FormData constructor | ||
if (isstr(init.qs)) init.qs = parseQueryString(init.qs) | ||
url.search = createQueryString(assign(fromEntries([...url.searchParams.entries()]), init.qs)) | ||
url.search = createQueryString( | ||
assign( | ||
fromEntries([...url.searchParams.entries()]), | ||
init.qs | ||
) | ||
) | ||
} | ||
@@ -107,3 +139,5 @@ // same-origin by default | ||
} | ||
return XResponsePromise.resolve(init.fetch(url, init).then(responseErrorThrower)) | ||
return XResponsePromise.resolve( | ||
init.fetch(url, init).then(responseErrorThrower) | ||
) | ||
} | ||
@@ -117,3 +151,4 @@ for (const method of METHODS) { | ||
// Extra methods and classes | ||
xfetch.extend = newDefaultInit => extend(assign({}, defaultInit, newDefaultInit)) | ||
xfetch.extend = newDefaultInit => | ||
extend(assign({}, defaultInit, newDefaultInit)) | ||
xfetch.HTTPError = HTTPError | ||
@@ -120,0 +155,0 @@ return xfetch |
@@ -27,7 +27,11 @@ import test from 'ava' | ||
test('post urlencoded:string', async t => { | ||
const { form } = await client.post('/post', { urlencoded: 'foo=bar' }).json() | ||
const { form } = await client | ||
.post('/post', { urlencoded: 'foo=bar' }) | ||
.json() | ||
t.deepEqual(form, { foo: 'bar' }) | ||
}) | ||
test('post urlencoded:object', async t => { | ||
const { form } = await client.post('/post', { urlencoded: { foo: 'bar' } }).json() | ||
const { form } = await client | ||
.post('/post', { urlencoded: { foo: 'bar' } }) | ||
.json() | ||
t.deepEqual(form, { foo: 'bar' }) | ||
@@ -71,3 +75,5 @@ }) | ||
.get('/get') | ||
.json(({ headers }) => client.post('/post', { json: { host: headers.host } })) | ||
.json(({ headers }) => | ||
client.post('/post', { json: { host: headers.host } }) | ||
) | ||
.json() | ||
@@ -77,3 +83,5 @@ t.is(data.host, 'postman-echo.com') | ||
test('headers', async t => { | ||
const { headers } = await client.get('/get', { headers: { 'x-test': 'hello' } }).json() | ||
const { headers } = await client | ||
.get('/get', { headers: { 'x-test': 'hello' } }) | ||
.json() | ||
t.is(headers['x-test'], 'hello') | ||
@@ -87,2 +95,16 @@ }) | ||
}) | ||
test('headers: Overwrite prevention (JSON)', async t => { | ||
const h = new Headers() | ||
h.append('Content-Type', 'application/nosj') | ||
const { headers } = await client.get('/get', { headers: h }).json() | ||
t.is(headers['content-type'], 'application/nosj') | ||
}) | ||
test('headers: Overwrite prevention (URL Encoded)', async t => { | ||
const h = new Headers() | ||
h.append('Content-Type', 'application/lru') | ||
const { headers } = await client | ||
.post('/post', { headers: h, urlencoded: { foo: 'bar' } }) | ||
.json() | ||
t.is(headers['content-type'], 'application/lru') | ||
}) | ||
test('HTTPError', async t => { | ||
@@ -102,3 +124,8 @@ await t.throwsAsync(client.get('/404'), { | ||
}) | ||
const r = await client2.get('/get', { headers: { 'Content-Type': 'application/json' }, qs: { q: 'test' } }).json() | ||
const r = await client2 | ||
.get('/get', { | ||
headers: { 'Content-Type': 'application/json' }, | ||
qs: { q: 'test' } | ||
}) | ||
.json() | ||
t.is(r.headers['authorization'], 'Bearer asdfghjkl') | ||
@@ -105,0 +132,0 @@ t.is(r.headers['content-type'], 'application/json') |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
18989
365
4