UNPKG

wretch

Version:

A tiny wrapper built around fetch with an intuitive syntax.

3 lines (2 loc) 6.94 kB
const e=Symbol();function r(e={}){var r;return null===(r=Object.entries(e).find((([e])=>e.toLowerCase()==="Content-Type".toLowerCase())))||void 0===r?void 0:r[1]}function t(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})},n={options:{},errorType:"text",polyfills:{},polyfill(e,r=1,t=0,...o){const n=this.polyfills[e]||("undefined"!=typeof self?self[e]:null)||("undefined"!=typeof global?global[e]:null);if(r&&!n)throw new Error(e+" is not defined");return t&&n?new n(...o):n}};class s extends Error{}const i=r=>{const{_url:t,_options:n,_config:i,_catchers:l,_resolvers:c,_middlewares:a,_addons:u}=r,h=new Map(l),f=o(i.options,n);u.forEach((e=>e.beforeRequest&&e.beforeRequest(r,f)));const p=(e=>r=>e.reduceRight(((e,r)=>r(e)),r)||r)(a)(i.polyfill("fetch"))(t,f),d=new Error,_=p.catch((e=>{throw{__wrap:e}})).then((e=>{if(!e.ok){const r=new s;if(r.cause=d,r.stack=r.stack+"\nCAUSE: "+d.stack,r.response=e,"opaque"===e.type)throw r;return e[i.errorType]().then((t=>{throw r.message=t,r[i.errorType]=t,r.status=e.status,r}))}return e})),y=t=>o=>(t?_.then((e=>e&&e[t]())).then((e=>o?o(e):e)):_.then((e=>o?o(e):e))).catch((t=>{const o=t.__wrap||t,n=t.__wrap&&h.has(e)?h.get(e):h.get(o.status)||h.get(o.name);if(n)return n(o,r);throw o})),b={_wretchReq:r,_fetchReq:p,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(r){return this.error(e,r)}},g=u.reduce(((e,r)=>({...e,...r.resolver})),b);return c.reduce(((e,t)=>t(e,r)),g)},l={_url:"",_options:{},_config:n,_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(e){return this.headers({"Content-Type":e})},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,o="",n=null){let s=this.url(o).options({method:e});const l=r(s._options.headers),c="object"==typeof n&&(!s._options.headers||!l||t(l));return s=n?c?s.json(n,l):s.body(n):s,i(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,o){const n=r(this._options.headers);return this.content(o||t(n)&&n||"application/json").body(JSON.stringify(e))}},c=()=>{let e=null,r=null;return{beforeRequest(t,o){r=t._config.polyfill("AbortController",0,1),!o.signal&&r&&(o.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,o=r){return e.clear(),e.ref=setTimeout((()=>o.abort()),t),this},controller(){return[r,this]},onAbort(e){return this.error("AbortError",e)}}}};function a(e,r=0,t,o=t.polyfill("FormData",1,1),n=[]){return Object.entries(e).forEach((([e,s])=>{let i=n.reduce(((e,r)=>e?`${e}[${r}]`:r),null);if(i=i?`${i}[${e}]`:e,s instanceof Array)for(const e of s)o.append(i,e);else!r||"object"!=typeof s||r instanceof Array&&r.includes(e)?o.append(i,s):null!==s&&a(s,r,t,o,[...n,e])})),o}const u={wretch:{formData(e,r=0){return this.body(a(e,r,this._config))}}};function h(e,r){return encodeURIComponent(e)+"="+encodeURIComponent("object"==typeof r?JSON.stringify(r):""+r)}const f={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=>h(e,r))).join("&"):h(e,t)})).join("&"))).content("application/x-www-form-urlencoded");var r}}},p=(e,r,t,o)=>{if(!e.getEntriesByName)return 0;const n=e.getEntriesByName(r);return n&&n.length>0?(t(n.reverse()[0]),o.clearMeasures&&o.clearMeasures(r),d.callbacks.delete(r),d.callbacks.size<1&&(d.observer.disconnect(),o.clearResourceTimings&&o.clearResourceTimings()),1):0},d={callbacks:new Map,observer:null,observe:(e,r,t)=>{if(!e||!r)return;const o=t.polyfill("performance",0);((e,r)=>(!d.observer&&e&&r&&(d.observer=new r((r=>{d.callbacks.forEach(((t,o)=>{p(r,o,t,e)}))})),e.clearResourceTimings&&e.clearResourceTimings()),d.observer))(o,t.polyfill("PerformanceObserver",0))&&(p(o,e,r,o)||(d.callbacks.size<1&&d.observer.observe({entryTypes:["resource","measure"]}),d.callbacks.set(e,r)))}},_=()=>({resolver:{perfs(e){return this._fetchReq.then((r=>d.observe(r.url,e,this._wretchReq._config))).catch((()=>{})),this}}});function y(e){return void 0!==e?e:""}const b=(e,r,t,o)=>{let n;if("string"==typeof r)n=r;else{const e=o.polyfill("URLSearchParams",1,1);for(const t in r){const o=r[t];if(r[t]instanceof Array)for(const r of o)e.append(t,y(r));else e.append(t,y(o))}n=e.toString()}const s=e.split("?");return n?t||s.length<2?s[0]+"?"+n:e+"&"+n:t?s[0]:e},g={wretch:{query(e,r=0){return{...this,_url:b(this._url,e,r,this._config)}}}},m=()=>{const e={ref:null},r=r=>(t,o)=>{let n=0,s=0;return r(t,o).then((r=>{try{const t=r.headers.get("content-length");s=t?+t:null;const o=new TransformStream({transform(r,t){n+=r.length,s<n&&(s=n),e.ref&&e.ref(n,s),t.enqueue(r)}});return new Response(r.body.pipeThrough(o),r)}catch(e){return r}}))};return{beforeRequest:e=>e._middlewares.push(r),resolver:{progress(r){return e.ref=r,this}}}};function w(e="",r={}){return{...l,_url:e,_options:r}.addon(c()).addon(u).addon(f).addon(_()).addon(g).addon(m())}w.default=w,w.options=function(e,r=0){n.options=r?e:o(n.options,e)},w.errorType=function(e){n.errorType=e},w.polyfills=function(e,r=0){n.polyfills=r?e:o(n.polyfills,e)},w.WretchError=s,module.exports=w; //# sourceMappingURL=wretch.all.min.cjs.map