UNPKG

axios-multi-api

Version:

Fast, lightweight and reusable data fetching

2 lines 7.92 kB
async function b(o,e){if(!e)return o;let s=Array.isArray(e)?e:[e],t={...o};for(let n of s)t=await n(t);return t}async function P(o,e){if(!e)return o;let s=Array.isArray(e)?e:[e],t=o;for(let n of s)t=await n(t);return t}var g=class extends Error{response;request;config;status;statusText;constructor(e,s,t){super(e),this.name="ResponseError",this.message=e,this.status=t.status,this.statusText=t.statusText,this.request=s,this.config=s,this.response=t}};function A(o,e){if(!e)return o;if(e instanceof URLSearchParams){let a=e.toString();return o.includes("?")?`${o}&${a}`:a?`${o}?${a}`:o}let s=[],t=function(a,r){r=typeof r=="function"?r():r,r=r===null||r===void 0?"":r,s[s.length]=encodeURIComponent(a)+"="+encodeURIComponent(r)},n=(a,r)=>{let i,c,p;if(a)if(Array.isArray(r))for(i=0,c=r.length;i<c;i++)n(a+"["+(typeof r[i]=="object"&&r[i]?i:"")+"]",r[i]);else if(typeof r=="object"&&r!==null)for(p in r)n(a+"["+p+"]",r[p]);else t(a,r);else if(Array.isArray(r))for(i=0,c=r.length;i<c;i++)t(r[i].name,r[i].value);else for(p in r)n(p,r[p]);return s},u=n("",e).join("&").replace(/%5B%5D/g,"[]");return o.includes("?")?`${o}&${u}`:u?`${o}?${u}`:o}function D(o,e){return e?o.replace(/:[a-zA-Z]+/gi,s=>{let t=s.substring(1);return String(e[t]?e[t]:s)}):o}function F(o){if(o==null)return!1;let e=typeof o;if(e==="string"||e==="number"||e==="boolean")return!0;if(e!=="object")return!1;if(Array.isArray(o))return!0;if(Buffer.isBuffer(o)||o instanceof Date)return!1;let s=Object.getPrototypeOf(o);return s===Object.prototype||s===null||typeof o.toJSON=="function"}async function E(o){return new Promise(e=>setTimeout(()=>e(!0),o))}var C="application/json",h=class{requestInstance;baseURL="";timeout=3e4;cancellable=!1;rejectCancelled=!1;strategy="reject";method="get";flattenResponse=!1;defaultResponse=null;fetcher;logger;onError;requestsQueue;retry={retries:0,delay:1e3,maxDelay:3e4,backoff:1.5,retryOn:[408,409,425,429,500,502,503,504],shouldRetry:async()=>!0};config;constructor({fetcher:e=null,timeout:s=null,rejectCancelled:t=!1,strategy:n=null,flattenResponse:l=null,defaultResponse:u={},logger:a=null,onError:r=null,...i}){this.fetcher=e,this.timeout=s??this.timeout,this.strategy=n||this.strategy,this.cancellable=i.cancellable||this.cancellable,this.rejectCancelled=t||this.rejectCancelled,this.flattenResponse=l||this.flattenResponse,this.defaultResponse=u,this.logger=a||(globalThis?globalThis.console:null)||null,this.onError=r,this.requestsQueue=new WeakMap,this.baseURL=i.baseURL||i.apiUrl||"",this.method=i.method||this.method,this.config=i,this.retry={...this.retry,...i.retry||{}},this.requestInstance=this.isCustomFetcher()?e.create({...i,baseURL:this.baseURL,timeout:this.timeout}):null}getInstance(){return this.requestInstance}buildConfig(e,s,t){let n=(t.method||this.method).toUpperCase(),l=n==="GET"||n==="HEAD",u=D(e,t.urlPathParams||this.config.urlPathParams),a=t.params||this.config.params,r=t.body||t.data||this.config.body||this.config.data,i=!!(s&&(l||r)),c;if(l||(c=r||s),this.isCustomFetcher())return{...t,method:n,url:u,params:i?s:a,data:c};let p=t.withCredentials||this.config.withCredentials?"include":t.credentials;delete t.data,delete t.withCredentials;let R=a||i?A(u,a||s):u,f=R.includes("://")?"":t.baseURL||this.baseURL;return c&&typeof c!="string"&&!(c instanceof URLSearchParams)&&F(c)&&(c=JSON.stringify(c)),{...t,credentials:p,body:c,method:n,url:f+R,headers:{Accept:C+", text/plain, */*","Content-Type":C+";charset=utf-8",...t.headers||this.config.headers||{}}}}processError(e,s){var t;this.isRequestCancelled(e)||((t=this.logger)!=null&&t.warn&&this.logger.warn("API ERROR",e),s.onError&&typeof s.onError=="function"&&s.onError(e),this.onError&&typeof this.onError=="function"&&this.onError(e))}async outputErrorResponse(e,s){let t=this.isRequestCancelled(e),n=s.strategy||this.strategy,l=typeof s.rejectCancelled<"u"?s.rejectCancelled:this.rejectCancelled,u=typeof s.defaultResponse<"u"?s.defaultResponse:this.defaultResponse;return n==="softFail"?this.outputResponse(e.response,s,e):t&&!l?u:n==="silent"?(await new Promise(()=>null),u):n==="reject"?Promise.reject(e):u}isRequestCancelled(e){return e.name==="AbortError"||e.name==="CanceledError"}isCustomFetcher(){return this.fetcher!==null}addCancellationToken(e){if(!this.cancellable&&!e.cancellable)return{};if(typeof e.cancellable<"u"&&!e.cancellable)return{};if(typeof AbortController>"u")return console.error("AbortController is unavailable."),{};let s=this.requestsQueue.get(e);s&&s.abort();let t=new AbortController;if(!this.isCustomFetcher()&&this.timeout>0){let n=setTimeout(()=>{let l=new Error(`[TimeoutError]: The ${e.url} request was aborted due to timeout`);throw l.name="TimeoutError",l.code=23,t.abort(l),clearTimeout(n),l},e.timeout||this.timeout)}return this.requestsQueue.set(e,t),{signal:t.signal}}async request(e,s=null,t=null){var w,q;let n=null,l=t||{},u=this.buildConfig(e,s,l),a={...this.addCancellationToken(u),...u},{retries:r,delay:i,backoff:c,retryOn:p,shouldRetry:R,maxDelay:y}={...this.retry,...(a==null?void 0:a.retry)||{}},f=0,m=i;for(;f<=r;)try{if(a=await b(a,a.onRequest),a=await b(a,this.config.onRequest),this.isCustomFetcher())n=await this.requestInstance.request(a);else if(n=await globalThis.fetch(a.url,a),n.config=a,n.data=await this.parseData(n),!n.ok)throw new g(`${a.url} failed! Status: ${n.status||null}`,a,n);return n=await P(n,a.onResponse),n=await P(n,this.config.onResponse),this.outputResponse(n,a)}catch(d){if(f===r||!await R(d,f)||!(p!=null&&p.includes(((w=d==null?void 0:d.response)==null?void 0:w.status)||(d==null?void 0:d.status))))return this.processError(d,a),this.outputErrorResponse(d,a);(q=this.logger)!=null&&q.warn&&this.logger.warn(`Attempt ${f+1} failed. Retrying in ${m}ms...`),await E(m),m*=c,m=Math.min(m,y),f++}return this.outputResponse(n,a)}async parseData(e){var n;if(!e.body)return null;let s=String(((n=e.headers)==null?void 0:n.get("Content-Type"))||"").split(";")[0],t;try{if(s.includes(C)||s.includes("+json"))t=await e.json();else if(s.includes("multipart/form-data"))t=await e.formData();else if(s.includes("application/octet-stream"))t=await e.blob();else if(s.includes("application/x-www-form-urlencoded"))t=await e.formData();else if(s.includes("text/"))t=await e.text();else try{t=await e.clone().json()}catch{t=await e.text()}}catch{t=null}return t}processHeaders(e){let s=e.headers;if(!s)return{};let t={};if(s instanceof Headers)s.forEach((n,l)=>{t[l]=n});else if(typeof s=="object"&&s!==null)for(let[n,l]of Object.entries(s))t[n.toLowerCase()]=l;return t}outputResponse(e,s,t=null){let n=typeof s.defaultResponse<"u"?s.defaultResponse:this.defaultResponse;return e?(s.flattenResponse||this.flattenResponse)&&typeof e.data<"u"?e.data!==null&&typeof e.data=="object"&&typeof e.data.data<"u"&&Object.keys(e.data).length===1?e.data.data:e.data:e!==null&&typeof e=="object"&&e.constructor===Object&&Object.keys(e).length===0?n:this.isCustomFetcher()?e:(t!==null&&(t==null||delete t.response,t==null||delete t.request,t==null||delete t.config),{body:e.body,blob:e.blob,json:e.json,text:e.text,clone:e.clone,bodyUsed:e.bodyUsed,arrayBuffer:e.arrayBuffer,formData:e.formData,ok:e.ok,redirected:e.redirected,type:e.type,url:e.url,status:e.status,statusText:e.statusText,error:t,data:e.data,headers:this.processHeaders(e),config:s}):n}};function L(o){let e=o.endpoints,s=new h(o);function t(){return s.getInstance()}function n(r){return console.error(`${r} endpoint must be added to 'endpoints'.`),Promise.resolve(null)}async function l(r,i={},c={},p={}){let y={...e[r]};return await s.request(y.url,i,{...y,...p,urlPathParams:c})}function u(r){return r in a?a[r]:e[r]?a.request.bind(null,r):n.bind(null,r)}let a={config:o,endpoints:e,requestHandler:s,getInstance:t,request:l};return new Proxy(a,{get:(r,i)=>u(i)})}async function B(o,e={}){return new h(e).request(o,null,e)}export{L as createApiFetcher,B as fetchf}; //# sourceMappingURL=index.mjs.map