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 2.07 kB
"use strict";var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,a={};((e,r)=>{for(var s in r)t(e,s,{get:r[s],enumerable:!0})})(a,{FetchAdapter:()=>c,HttpError:()=>i}),module.exports=(e=a,((e,a,o,i)=>{if(a&&"object"===typeof a||"function"===typeof a)for(let c of s(a))n.call(e,c)||c===o||t(e,c,{get:()=>a[c],enumerable:!(i=r(a,c))||i.enumerable});return e})(t({},"__esModule",{value:!0}),e));var o=require("./interceptor-manager");class i extends Error{constructor(e,t,r){super(r||t),this.status=e,this.statusText=t,this.name="HttpError"}}class c{constructor(e,t=globalThis.fetch){this.baseURL="",this.headers={},this.interceptors=new o.InterceptorManager,e&&(this.baseURL=e),this.fetchFn=t.bind(globalThis)}init(e){this.baseURL=e.baseURL}addHeaders(e){this.headers={...this.headers,...e}}buildUrl(e,t){const r=new URL(e,this.baseURL);return t&&(r.search=new URLSearchParams(t).toString()),r.toString()}mergeHeaders(e){return{...this.headers,...e}}processBody(e,t){return e instanceof FormData||e instanceof URLSearchParams||e instanceof Blob||"string"===typeof e?e:(t["Content-Type"]||t["content-type"]||(t["Content-Type"]="application/json"),JSON.stringify(e))}async parseResponse(e){const t=e.headers.get("Content-Type");return t?.includes("application/json")?e.json():e.text()}async request(e,t,r={}){const{searchParams:s,headers:n,body:a,signal:o,...c}=r,h=this.buildUrl(t,s),u=this.mergeHeaders(n);let p={url:h,method:e,headers:u,body:void 0!==a?this.processBody(a,u):void 0,signal:o,...c};p=await this.interceptors.executeRequestInterceptors(p);const d=await this.fetchFn(p.url,p),l=await this.interceptors.executeResponseInterceptors(d);if(!l.ok){const e=await l.text();throw new i(l.status,l.statusText,e)}return this.parseResponse(l)}get(e,t){return this.request("GET",e,t)}post(e,t,r){return this.request("POST",e,{...r,body:t})}put(e,t,r){return this.request("PUT",e,{...r,body:t})}patch(e,t,r){return this.request("PATCH",e,{...r,body:t})}delete(e,t){return this.request("DELETE",e,t)}}