UNPKG

wretch

Version:

A tiny wrapper built around fetch with an intuitive syntax.

3 lines (2 loc) 7.15 kB
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e="undefined"!=typeof globalThis?globalThis:e||self).wretch=r()}(this,(function(){const e="Content-Type",r=Symbol();function t(r={}){var t;return null===(t=Object.entries(r).find((([r])=>r.toLowerCase()===e.toLowerCase())))||void 0===t?void 0:t[1]}function n(e){return/^application\/.*json.*/.test(e)}const o=function(e,r,t=0){return Object.entries(r).reduce(((r,[n,s])=>{const i=e[n];return Array.isArray(i)&&Array.isArray(s)?r[n]=t?[...i,...s]:s:r[n]="object"==typeof i&&"object"==typeof s?o(i,s,t):s,r}),{...e})},s={options:{},errorType:"text",polyfills:{},polyfill(e,r=1,t=0,...n){const o=this.polyfills[e]||("undefined"!=typeof self?self[e]:null)||("undefined"!=typeof global?global[e]:null);if(r&&!o)throw new Error(e+" is not defined");return t&&o?new o(...n):o}};class i extends Error{}const l=e=>{const{_url:t,_options:n,_config:s,_catchers:l,_resolvers:c,_middlewares:u,_addons:a}=e,h=new Map(l),f=o(s.options,n);a.forEach((r=>r.beforeRequest&&r.beforeRequest(e,f)));const d=(e=>r=>e.reduceRight(((e,r)=>r(e)),r)||r)(u)(s.polyfill("fetch"))(t,f),p=new Error,_=d.catch((e=>{throw{__wrap:e}})).then((e=>{if(!e.ok){const r=new i;if(r.cause=p,r.stack=r.stack+"\nCAUSE: "+p.stack,r.response=e,"opaque"===e.type)throw r;return e[s.errorType]().then((t=>{throw r.message=t,r[s.errorType]=t,r.status=e.status,r}))}return e})),y=t=>n=>(t?_.then((e=>e&&e[t]())).then((e=>n?n(e):e)):_.then((e=>n?n(e):e))).catch((t=>{const n=t.__wrap||t,o=t.__wrap&&h.has(r)?h.get(r):h.get(n.status)||h.get(n.name);if(o)return o(n,e);throw n})),b={_wretchReq:e,_fetchReq:d,res:y(null),json:y("json"),blob:y("blob"),formData:y("formData"),arrayBuffer:y("arrayBuffer"),text:y("text"),error(e,r){return h.set(e,r),this},badRequest(e){return this.error(400,e)},unauthorized(e){return this.error(401,e)},forbidden(e){return this.error(403,e)},notFound(e){return this.error(404,e)},timeout(e){return this.error(408,e)},internalError(e){return this.error(500,e)},fetchError(e){return this.error(r,e)}},g=a.reduce(((e,r)=>({...e,...r.resolver})),b);return c.reduce(((r,t)=>t(r,e)),g)},c={_url:"",_options:{},_config:s,_catchers:new Map,_resolvers:[],_deferred:[],_middlewares:[],_addons:[],addon(e){return{...this,_addons:[...this._addons,e],...e.wretch}},errorType(e){return{...this,_config:{...this._config,errorType:e}}},polyfills(e,r=0){return{...this,_config:{...this._config,polyfills:r?e:o(this._config.polyfills,e)}}},url(e,r=0){if(r)return{...this,_url:e};const t=this._url.split("?");return{...this,_url:t.length>1?t[0]+e+"?"+t[1]:this._url+e}},options(e,r=0){return{...this,_options:r?e:o(this._options,e)}},headers(e){return{...this,_options:o(this._options,{headers:e||{}})}},accept(e){return this.headers({Accept:e})},content(r){return this.headers({[e]:r})},auth(e){return this.headers({Authorization:e})},catcher(e,r){const t=new Map(this._catchers);return t.set(e,r),{...this,_catchers:t}},resolve(e,r=0){return{...this,_resolvers:r?[e]:[...this._resolvers,e]}},defer(e,r=0){return{...this,_deferred:r?[e]:[...this._deferred,e]}},middlewares(e,r=0){return{...this,_middlewares:r?e:[...this._middlewares,...e]}},fetch(e=this._options.method,r="",o=null){let s=this.url(r).options({method:e});const i=t(s._options.headers),c="object"==typeof o&&(!s._options.headers||!i||n(i));return s=o?c?s.json(o,i):s.body(o):s,l(s._deferred.reduce(((e,r)=>r(e,e._url,e._options)),s))},get(e=""){return this.fetch("GET",e)},delete(e=""){return this.fetch("DELETE",e)},put(e,r=""){return this.fetch("PUT",r,e)},post(e,r=""){return this.fetch("POST",r,e)},patch(e,r=""){return this.fetch("PATCH",r,e)},head(e=""){return this.fetch("HEAD",e)},opts(e=""){return this.fetch("OPTIONS",e)},body(e){return{...this,_options:{...this._options,body:e}}},json(e,r){const o=t(this._options.headers);return this.content(r||n(o)&&o||"application/json").body(JSON.stringify(e))}},u=()=>{let e=null,r=null;return{beforeRequest(t,n){r=t._config.polyfill("AbortController",0,1),!n.signal&&r&&(n.signal=r.signal),e={ref:null,clear(){e.ref&&(clearTimeout(e.ref),e.ref=null)}}},wretch:{signal(e){return{...this,_options:{...this._options,signal:e.signal}}}},resolver:{setTimeout(t,n=r){return e.clear(),e.ref=setTimeout((()=>n.abort()),t),this},controller(){return[r,this]},onAbort(e){return this.error("AbortError",e)}}}};function a(e,r=0,t,n=t.polyfill("FormData",1,1),o=[]){return Object.entries(e).forEach((([e,s])=>{let i=o.reduce(((e,r)=>e?`${e}[${r}]`:r),null);if(i=i?`${i}[${e}]`:e,s instanceof Array)for(const e of s)n.append(i,e);else!r||"object"!=typeof s||r instanceof Array&&r.includes(e)?n.append(i,s):null!==s&&a(s,r,t,n,[...o,e])})),n}const h={wretch:{formData(e,r=0){return this.body(a(e,r,this._config))}}};function f(e,r){return encodeURIComponent(e)+"="+encodeURIComponent("object"==typeof r?JSON.stringify(r):""+r)}const d={wretch:{formUrl(e){return this.body("string"==typeof e?e:(r=e,Object.keys(r).map((e=>{const t=r[e];return t instanceof Array?t.map((r=>f(e,r))).join("&"):f(e,t)})).join("&"))).content("application/x-www-form-urlencoded");var r}}},p=(e,r,t,n)=>{if(!e.getEntriesByName)return 0;const o=e.getEntriesByName(r);return o&&o.length>0?(t(o.reverse()[0]),n.clearMeasures&&n.clearMeasures(r),_.callbacks.delete(r),_.callbacks.size<1&&(_.observer.disconnect(),n.clearResourceTimings&&n.clearResourceTimings()),1):0},_={callbacks:new Map,observer:null,observe:(e,r,t)=>{if(!e||!r)return;const n=t.polyfill("performance",0);((e,r)=>(!_.observer&&e&&r&&(_.observer=new r((r=>{_.callbacks.forEach(((t,n)=>{p(r,n,t,e)}))})),e.clearResourceTimings&&e.clearResourceTimings()),_.observer))(n,t.polyfill("PerformanceObserver",0))&&(p(n,e,r,n)||(_.callbacks.size<1&&_.observer.observe({entryTypes:["resource","measure"]}),_.callbacks.set(e,r)))}},y=()=>({resolver:{perfs(e){return this._fetchReq.then((r=>_.observe(r.url,e,this._wretchReq._config))).catch((()=>{})),this}}});function b(e){return void 0!==e?e:""}const g=(e,r,t,n)=>{let o;if("string"==typeof r)o=r;else{const e=n.polyfill("URLSearchParams",1,1);for(const t in r){const n=r[t];if(r[t]instanceof Array)for(const r of n)e.append(t,b(r));else e.append(t,b(n))}o=e.toString()}const s=e.split("?");return o?t||s.length<2?s[0]+"?"+o:e+"&"+o:t?s[0]:e},m={wretch:{query(e,r=0){return{...this,_url:g(this._url,e,r,this._config)}}}},w=()=>{const e={ref:null},r=r=>(t,n)=>{let o=0,s=0;return r(t,n).then((r=>{try{const t=r.headers.get("content-length");s=t?+t:null;const n=new TransformStream({transform(r,t){o+=r.length,s<o&&(s=o),e.ref&&e.ref(o,s),t.enqueue(r)}});return new Response(r.body.pipeThrough(n),r)}catch(e){return r}}))};return{beforeRequest:e=>e._middlewares.push(r),resolver:{progress(r){return e.ref=r,this}}}};function T(e="",r={}){return{...c,_url:e,_options:r}.addon(u()).addon(h).addon(d).addon(y()).addon(m).addon(w())}return T.default=T,T.options=function(e,r=0){s.options=r?e:o(s.options,e)},T.errorType=function(e){s.errorType=e},T.polyfills=function(e,r=0){s.polyfills=r?e:o(s.polyfills,e)},T.WretchError=i,T})); //# sourceMappingURL=wretch.all.min.js.map