UNPKG

@bishal-shrestha/rest-client

Version:

A lightweight and flexible REST API client for JavaScript and TypeScript, supporting CommonJS and ES modules (ESM). Features include HTTP methods (GET, POST, PUT, PATCH, DELETE), built-in retry policies with exponential backoff, request lifecycle hooks fo

3 lines (2 loc) 3.94 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).RestClient={})}(this,function(t){"use strict";function e(t,e,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(t):s?s.value:e.get(t)}function n(t){return new Promise(e=>setTimeout(e,t))}function s(t){return[502,503,504].includes(t.status)}"function"==typeof SuppressedError&&SuppressedError;class r{constructor({timeout:t=1e4,maxRetries:e=0,shouldRetry:r=s,delayFn:o=n,onRequestStart:i=null,onRequestEnd:a=null,onRequestError:l=null}={}){this.timeout=t,this.maxRetries=e,this.shouldRetry=r,this.delayFn=o,this.onRequestStart=i,this.onRequestEnd=a,this.onRequestError=l}}var o,i;class a{constructor(t,e={},n=new r){if(o.add(this),!t||"string"!=typeof t)throw new TypeError("Base URL must be a non-empty string");this.baseUrl=t.replace(/\/+$/,""),this.defaultHeaders={"Content-Type":"application/json",...e},this.timeout=n.timeout??1e4,this.maxRetries=n.maxRetries??0,this.shouldRetry=n.shouldRetry||(t=>[502,503,504].includes(t.status)),this.delayFn=n.delayFn??(t=>new Promise(e=>setTimeout(e,t))),this.onRequestStart=n.onRequestStart,this.onRequestEnd=n.onRequestEnd,this.onRequestError=n.onRequestError}setHeaders(t){this.defaultHeaders={...this.defaultHeaders,...t}}async getAsync(t=null,n={},s={},r=null){const a=function(t="",e={}){const n=t||"",s=new URLSearchParams;for(const[t,n]of Object.entries(e))null!=n&&s.append(t,String(n));if(0===[...s].length)return n;const r=n.includes("?")?"&":"?";return`${n}${r}${s.toString()}`}(t,n);return await e(this,o,"m",i).call(this,"GET",a,null,s,0,r)}async postAsync(t=null,n,s={},r=null){return e(this,o,"m",i).call(this,"POST",t,n,s,0,r)}async putAsync(t=null,n,s={},r=null){return e(this,o,"m",i).call(this,"PUT",t,n,s,0,r)}async patchAsync(t=null,n,s={},r=null){return e(this,o,"m",i).call(this,"PATCH",t,n,s,0,r)}async deleteAsync(t=null,n={},s=null){return e(this,o,"m",i).call(this,"DELETE",t,null,n,0,s)}}o=new WeakSet,i=async function t(n,s,r,i,a=0,l=null){const u=function(t,e){return e?/^https?:\/\//i.test(e)?e:`${t}/${e.replace(/^\/+/,"")}`:t}(this.baseUrl,s),c={...this.defaultHeaders,...i},h=Object.keys(c).find(t=>"content-type"===t.toLowerCase()),d=h?c[h]:"application/json",f={method:n,headers:c};null!==r&&"GET"!==n&&"HEAD"!==n&&(d.includes("application/json")?f.body=JSON.stringify(r):r instanceof FormData||r instanceof URLSearchParams?(f.body=r,delete c["Content-Type"]):f.body=r);const y=l||new AbortController,p=setTimeout(()=>y.abort(),this.timeout);f.signal=y.signal,this.onRequestStart?.(n,u,f);try{const c=await fetch(u,f);if(this.onRequestEnd?.(c),!c.ok){if(this.maxRetries>0&&a<this.maxRetries&&this.shouldRetry(c)){const u=function(t){return Math.min(8e3,500*2**t)}(a);return await this.delayFn(u),e(this,o,"m",t).call(this,n,s,r,i,a+1,l)}const u=`HTTP ${c.status} - ${c.statusText}`,h=(c.headers.get("content-type")||"").toLowerCase().includes("application/json")?await c.json():await c.text(),d=new Error(u);throw d.status=c.status,d.details=h,d}if(204===c.status)return null;return(c.headers.get("content-type")||"").toLowerCase().includes("application/json")?await c.json():await c.text()}catch(t){if(this.onRequestError?.(t),t instanceof Error&&"AbortError"===t.name)throw new Error(`Request to ${u} timed out after ${this.timeout} ms`);if(t instanceof TypeError&&t.message.includes("fetch"))throw new Error(`Network error while connecting to ${u}`);throw t}finally{clearTimeout(p)}},t.RestClient=a,t.RestClientOptions=r,t.default=a,t.shouldRetry=s,Object.defineProperty(t,"__esModule",{value:!0})}); //# sourceMappingURL=rest-client.umd.min.js.map