UNPKG

@gruzf/request

Version:

An easy way to create an http request for NextJS and more

2 lines (1 loc) 3.74 kB
import x,{HTTPError as D}from"ky";import H from"../error.js";import{afterResponse as S,beforeRequestHook as C,supportsAbortController as U}from"../hooks/index.js";import{generateUrl as q,getUrl as I,isFormData as f}from"../utils/helpers.js";import T from"../utils/merge-headers.js";var V=["get","post","put","patch","del","head"],O=class{responseType;defaultData;defaultQueryParams;validHeaders;pathOptions;bodyEncoder;searchParamsEncoder;searchParamsParse;options;context;currentExecutingRequests={};constructor(e,t){this.update(e,t)}update(e,t){this.context=t;let{baseURL:s,responseType:r="json",defaultData:a,defaultQueryParams:c,validHeaders:h,pathOptions:n,bodyEncoder:i,searchParamsEncoder:u,searchParamsParse:y,requestAbort:m,hooks:P,...p}=e||{};this.responseType=r,this.defaultData={...a},this.validHeaders=h,this.pathOptions=n,this.bodyEncoder=i,this.searchParamsEncoder=u,this.searchParamsParse=y,c&&(this.defaultQueryParams=c);let d={...P};m&&U&&(d.afterResponse=[...d?.afterResponse??[],S.bind(this)],d.beforeRequest=[...d?.beforeRequest??[],C.bind(this)]),this.options={...p,hooks:d,prefixUrl:s}}updateOptions(e,t){this.update(e,t)}get http(){return x.create(this.options)}toSearchParams(e){if(!(!e||Object.keys(e).length===0))return this.searchParamsEncoder?this.searchParamsEncoder(e):new URLSearchParams(e)}clearVariables(e){if(f(e)){for(let t of e.keys())e.get(t)===void 0&&e.delete(t);return e}if(typeof e=="object"&&e!==null){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}}generateVariables(e,t,s){switch(this.clearVariables(t),e){case"head":return;case"get":case"del":{let r=this.toSearchParams({...this.defaultQueryParams,...this.defaultData,...s,...t});return r?{searchParams:r}:void 0}default:{let r=this.toSearchParams({...this.defaultQueryParams,...s}),a={...this.defaultData,...f(t)?{}:t};if(f(t)){let c=[...t?.entries()||[]].map(([h,n])=>{if(typeof n=="object"&&"size"in n&&"type"in n&&"name"in n&&"lastModified"in n&&n.size===0)return h}).filter(Boolean);for(let h of c)t.delete(h)}return{...r?{searchParams:r}:{},...!this.bodyEncoder&&Object.keys(a).length>0?{json:a}:{},...this.bodyEncoder&&Object.keys(a).length>0?{body:this.bodyEncoder(a)}:{},...f(t)?{body:t}:{}}}}}async getResponse(e,t){let s=await this.getResponseData(e,t),{status:r,headers:a}=e;return{status:r,headers:a,data:s}}async getResponseData(e,t){switch(this.responseType){case"json":try{return await e.json()}catch(s){return s instanceof Error?t||s.message:t||"fetch failed"}default:try{return await e.json()}catch(s){return s instanceof Error?t||s.message:t||"fetch failed"}}}generateMethod(e,t,s){let{vars:r,headers:a,...c}=t||{},{prefix:h="",pathOptions:n}=s||{};return this.clearVariables(r),async(...i)=>{let u=this.pathOptions?.(this.context?.req)||{},y=n?.(this.context?.req)||{},m={...u,...y},{path:P,baseUrl:p}=I(h,i[0]);p&&(this.options.prefixUrl=p);let[d,E,l]=q(P,r,m,this.searchParamsParse),{headers:k,...w}=i[1]||{},M=T(a,k,this.validHeaders),R={...w,...c,headers:M,searchParams:this.toSearchParams({...this.defaultQueryParams,...l})};if(e!=="head"){let o=i[2]&&"searchParams"in i[2]?i[2].searchParams:void 0,{headers:g,...b}=i[2]||{},j=T(a,g,this.validHeaders);R={...b,...c,headers:j,...this.generateVariables(e,i[1]||E,{...o,...l})}}try{let o=await this.http[e==="del"?"delete":e](d,R);return await this.getResponse(o)}catch(o){if(o instanceof D){let g=await this.getResponse(o.response,o.message);throw new H(g)}throw o instanceof Error&&typeof o.cause=="object"&&o.cause!==null&&"code"in o.cause&&o.cause instanceof Error&&o.cause.code==="ECONNREFUSED"?new Error(o.cause.message):o}}}methodsInstance(e,t){let s={};for(let r of V)s[r]=this.generateMethod(r,e,t);return s}},Y=O;export{O as Instance,Y as default};