UNPKG

@woogie0303/easyfetch

Version:

#### [한국어 버전](./README_KO.md)

2 lines (1 loc) 2.64 kB
"use strict";const e=["get","delete"],t=["patch","put","post"],r=["cache","credentials","headers","integrity","keepalive","method","mode","referrer","redirect","referrerPolicy","signal"];class s{requestCbArr;responseCbArr;constructor(){this.requestCbArr=[],this.responseCbArr=[]}request=(e,t)=>{this.requestCbArr.unshift([e,t])};response=(e,t)=>{this.responseCbArr.push([e,t])};async flushRequestInterceptors(e){const t=this.requestCbArr;let r=e;for(let e=0;e<t.length;e++)r=r.then(...t[e]);return r}async flushResPonseInterceptors(e){const t=this.responseCbArr;let r=e;for(let e=0;e<t.length;e++)r=r.then(...t[e]);return r}}const n=async(t,s)=>{const n=new Request(t,s),o=e.includes(n.method.toLowerCase());return r.reduce(((e,t)=>({...e,[t]:n[t]})),o?{}:{body:await n.arrayBuffer()})};class o{#e;#t;#r;constructor(e){this.#e=e?.baseUrl,this.#t=e?.headers,this.#r=new s}async request(e,t){if(e instanceof Request){const[r,s]=await(async(e,t)=>{const r=e.url;let s;if(t){const{next:r,priority:o,window:i,...c}=t;s={...await n(e,c),priority:o,window:i,next:r}}else s={...await n(e)};return[r,s]})(e,t);return this.#s(r,s)}return this.#s(e,t)}async#s(e,t){const r=this.#n(e,t),s=await this.#r.flushRequestInterceptors(Promise.resolve(r));return this.#r.flushResPonseInterceptors(this.#o(s[0],s[1]))}async#o(e,t){const r=fetch,s=new Headers(t?.headers);s.get("Content-Type")??s.set("Content-Type","application/json");try{const n=await r(e,{...t,headers:s}),o=await(async(e,t)=>{const r={headers:e.headers,ok:e.ok,redirected:e.redirected,status:e.status,statusText:e.statusText,type:e.type,config:[t[0],{...t[1]}]};try{const t=await e.json();return{...r,body:t}}catch(e){if("Unexpected end of JSON input"===e.message)return{...r,body:void 0};throw e}})(n,[e,{...t,headers:s}]);if(!n.ok||n.status<500&&n.status>=400||!(e=>!!e.body)(o))throw new Error(`${n.status} Error`,{cause:o});return Promise.resolve(o)}catch(e){if(e instanceof Error&&(n=e.cause,Object.keys(n).includes("config")))return Promise.reject(e.cause);throw e}var n}#n(e,t){let r,s;if(this.#e&&(r=new URL(e,this.#e)),this.#t){const e=new Headers(this.#t),r=new Headers(t?.headers);for(const[t,s]of e.entries())r.set(t,s);s={...t,headers:r}}return[r??e,s??t]}get interceptor(){return{request:this.#r.request,response:this.#r.response}}}const i=r=>{const s=new o(r);return[...t,...e].forEach((e=>{o.prototype[e]=function(e){return(e=>t.some((t=>t===e)))(e)?async function(t,r,s){const n={...s,body:r&&JSON.stringify(r),method:e.toUpperCase()};return this.request(t,n)}:async function(t,r){return this.request(t,{...r,method:e.toUpperCase()})}}(e)})),s},c=e=>i(e);exports.easyFetch=c;