UNPKG

@vegajs/http-client-adapter

Version:

A flexible, type-safe HTTP client adapter for TypeScript and JavaScript. Supports custom adapters and includes an out-of-the-box Axios adapter for easy HTTP request handling.

1 lines 1.65 kB
import{InterceptorManager as t}from"./interceptor-manager";class e extends Error{constructor(t,e,s){super(s||e),this.status=t,this.statusText=e,this.name="HttpError"}}class s{constructor(e,s=globalThis.fetch){this.baseURL="",this.headers={},this.interceptors=new t,e&&(this.baseURL=e),this.fetchFn=s.bind(globalThis)}init(t){this.baseURL=t.baseURL}addHeaders(t){this.headers={...this.headers,...t}}buildUrl(t,e){const s=new URL(t,this.baseURL);return e&&(s.search=new URLSearchParams(e).toString()),s.toString()}mergeHeaders(t){return{...this.headers,...t}}processBody(t,e){return t instanceof FormData||t instanceof URLSearchParams||t instanceof Blob||"string"===typeof t?t:(e["Content-Type"]||e["content-type"]||(e["Content-Type"]="application/json"),JSON.stringify(t))}async parseResponse(t){const e=t.headers.get("Content-Type");return e?.includes("application/json")?t.json():t.text()}async request(t,s,r={}){const{searchParams:n,headers:a,body:i,signal:o,...h}=r,c=this.buildUrl(s,n),u=this.mergeHeaders(a);let p={url:c,method:t,headers:u,body:void 0!==i?this.processBody(i,u):void 0,signal:o,...h};p=await this.interceptors.executeRequestInterceptors(p);const d=await this.fetchFn(p.url,p),l=await this.interceptors.executeResponseInterceptors(d);if(!l.ok){const t=await l.text();throw new e(l.status,l.statusText,t)}return this.parseResponse(l)}get(t,e){return this.request("GET",t,e)}post(t,e,s){return this.request("POST",t,{...s,body:e})}put(t,e,s){return this.request("PUT",t,{...s,body:e})}patch(t,e,s){return this.request("PATCH",t,{...s,body:e})}delete(t,e){return this.request("DELETE",t,e)}}export{s as FetchAdapter,e as HttpError};