UNPKG

@antoinette-agency/sofetch

Version:

An opinionated Fetch wrapper for JSON APIs

3 lines (2 loc) 10.7 kB
function q(n,o){return typeof document>"u"&&!o?void 0:(o||document.cookie).split("; ").map(t=>{let a=t.split("=");return{key:a[0],value:a[1]}}).find(t=>t.key===n)?.value}var f=class{constructor(){this.errorHandlers={};this.beforeSendHandlers=[];this.beforeFetchSendHandlers=[];this.onRequestCompleteHandlers=[];this.authTokenStorage=null;this.inMemoryAuthToken="";this.authenticationType=null;this.getAuthToken=async()=>{switch(this.authTokenStorage){case null:return"";case"memory":return this.inMemoryAuthToken;case"localStorage":return localStorage?.getItem(this.authenticationKey)||"";case"sessionStorage":return sessionStorage?.getItem(this.authenticationKey)||"";case"cookie":return q(this.authenticationKey)||"";default:return this.authTokenStorage()}};this.setAuthToken=o=>{switch(this.authTokenStorage){case"memory":this.inMemoryAuthToken=o;break;case"localStorage":localStorage.setItem(this.authenticationKey,o);break;case"sessionStorage":sessionStorage.setItem(this.authenticationKey,o);break;case"cookie":document.cookie=`${this.authenticationKey}=${o};`;break;default:break}};this.baseUrl="";this.authenticationKey="SOFETCH_AUTHENTICATION";this.authHeaderKey="";this.authQueryStringKey="";this.setAuthTokenStorage=o=>{if(o){this.authTokenStorage=o;return}o===null&&(this.authTokenStorage=null),this.authTokenStorage="memory"}}catchHTTP(o,i){this.errorHandlers[o]||(this.errorHandlers[o]=[]),this.errorHandlers[o].push(i)}beforeSend(o){this.beforeSendHandlers.push(o)}beforeFetchSend(o){this.beforeFetchSendHandlers.push(o)}onRequestComplete(o){this.onRequestCompleteHandlers.push(o)}useBearerAuthentication(o={}){let{authenticationKey:i,authTokenStorage:r,authToken:s}=o;this.authenticationType="bearer",i&&(this.authenticationKey=i),r===void 0&&(r=typeof document>"u"?"memory":"localStorage"),this.setAuthTokenStorage(r),s&&this.setAuthToken(s)}useCookieAuthentication(o){this.authenticationType="cookies";let i,r;o&&(i=o.authenticationKey,r=o.authToken),i&&(this.authenticationKey=i),this.authTokenStorage=typeof document>"u"?"memory":"cookie",r&&this.setAuthToken(r)}useHeaderAuthentication({headerKey:o,authToken:i,authenticationKey:r,authTokenStorage:s}){this.authenticationType="header",this.authHeaderKey=o,r&&(this.authenticationKey=r),this.setAuthTokenStorage(s),i&&this.setAuthToken(i)}useQueryStringAuthentication({queryStringKey:o,authToken:i,authenticationKey:r,authTokenStorage:s}){this.authenticationType="queryString",this.authQueryStringKey=o,r&&(this.authenticationKey=r),this.setAuthTokenStorage(s),i&&this.setAuthToken(i)}useBasicAuthentication({username:o,password:i,authenticationKey:r,authTokenStorage:s}){this.authenticationType="basic",(o&&!i||i&&!o)&&console.warn("Was expecting both username and password to be set for soFetch.config.useBasicAuthentication. Continuing but authentication may not behave as expected"),r&&(this.authenticationKey=r),this.setAuthTokenStorage(s),o&&i&&this.setBasicAuthCredentials({username:o,password:i})}setBasicAuthCredentials({username:o,password:i}){let r=btoa(`${o}:${i}`);this.setAuthToken(r)}};var g=class{constructor(o){this.errorHandlers={};this.beforeSendHandlers=[];this.beforeFetchSendHandlers=[];this.onRequestCompleteHandlers=[];this.timeout=3e4;this.inner=new Promise(o),this.then=this.inner.then.bind(this.inner),this.catch=this.inner.catch.bind(this.inner),this.finally=this.inner.finally.bind(this.inner)}onRequestComplete(o){return this.onRequestCompleteHandlers.push(o),this}beforeSend(o){return this.beforeSendHandlers.push(o),this}beforeFetchSend(o){return this.beforeFetchSendHandlers.push(o),this}catchHTTP(o,i){return this.errorHandlers[o]||(this.errorHandlers[o]=[]),this.errorHandlers[o].push(i),this}async setTimeout(o){return this.timeout=o,this}};function A(n){return new Promise(o=>setTimeout(o,n))}var v=n=>{let{isDefined:o,isArray:i,isFiles:r}=U(n);if(!o)return{};if(!r)return{jsonPayload:n};let s=i?n:[n];return{files:F(s[0])?s:s.map(((t,a)=>({file:t,fieldName:`file${a}`})))}},F=n=>"file"in n&&n.file instanceof File,U=n=>n?Array.isArray(n)?n.length?n[0]instanceof File?{isDefined:!0,isArray:!0,isFiles:!0}:F(n[0])?{isDefined:!0,isArray:!0,isFiles:!0}:{isDefined:!0,isArray:!0,isFiles:!1}:{isDefined:!1,isArray:!0,isFiles:!1}:n instanceof File?{isDefined:!0,isArray:!1,isFiles:!0}:F(n)?{isDefined:!0,isArray:!1,isFiles:!0}:{isDefined:!0,isArray:!1,isFiles:!1}:{isDefined:!1,isArray:!1,isFiles:!1};var R=(n,o)=>{let i=n.status,r=!!(o[i]&&o[i].length);return r&&o[i].forEach(s=>s(n)),r};var k=async(n,o)=>{for(let i of o)n=await i(n)||n;return n};var b=async(n,o)=>{for(let i of o)n=await i(n)||n;return n};async function I(n,o){let i=o.authenticationType===null?"":await o.getAuthToken();if(!i)return n;switch(o.authenticationType){case null:return n;case"basic":return n.headers.Authorization=`Basic ${i}`,n;case"bearer":return n.headers.Authorization=`Bearer ${i}`,n;case"header":return n.headers[o.authHeaderKey]=i,n;case"queryString":let r=new URL(n.url);return r.searchParams.append(o.authQueryStringKey,i),n.url=r.toString(),n;case"cookies":return typeof document>"u"&&(n.headers.Cookie=`${o.authenticationKey}=${i}`),n}}var E=async({url:n,method:o,body:i,config:r,promise:s})=>{let t={url:n,method:o,body:i,headers:{}};t.url=!r.baseUrl||t.url.startsWith("http")?t.url:`${r.baseUrl}${t.url}`,t=await I(t,r),t=await k(t,s.beforeSendHandlers),t=await k(t,r.beforeSendHandlers);let{files:a}=v(t.body),y=r.authenticationType==="cookies",u=a?N(t,a,y):D(t,y);return u=await b(u,s.beforeFetchSendHandlers),u=await b(u,r.beforeFetchSendHandlers),{init:u,finalUrl:t.url}},d=(n,o,i,r)=>{let s=new g((c,t)=>{(async()=>{await A(0);let{finalUrl:a,init:y}=await E({url:i,method:o,body:r,config:n,promise:s}),u=new Date().getTime(),l=await Promise.race([fetch(a,y),new Promise((m,T)=>setTimeout(()=>T(new Error("SoFetch timed out")),s.timeout))]),p=new Date().getTime()-u;h.verbose&&console.info(`SoFetch: ${o} ${l.status} ${a}`);for(let m of s.onRequestCompleteHandlers)await m(l,{duration:p,method:y.method||""});for(let m of n.onRequestCompleteHandlers)await m(l,{duration:p,method:y.method||""});if(!l.ok){let m=R(l,s.errorHandlers),T=!1;if(m||(T=R(l,n.errorHandlers)),!m&&!T)throw new Error(`Received response ${l.status} from URL ${l.url}`,{cause:l})}let C=await K(l);c(C)})().catch(a=>{t(a)})});return s},D=(n,o)=>{let{method:i,body:r}=n;return r&&(n.headers["Content-Type"]="application/json"),{body:r?JSON.stringify(r):void 0,headers:n.headers,method:i,credentials:o?"include":void 0}},N=(n,o,i)=>{let{method:r,headers:s}=n,c=new FormData;return o.forEach(a=>{c.append(a.fieldName,a.file,a.file.name)}),{body:c,headers:s,method:r,credentials:i?"include":void 0}},K=async n=>{if(n.status===203)return;let o=await n.text();if(!o)return;let i=o;try{i=JSON.parse(o)}catch{}return i},h=((n,o)=>d(h.config||new f,o?"POST":"GET",n,o));h.verbose=!1;h.config=new f;h.get=n=>d(h.config,"GET",n);h.post=(n,o)=>d(h.config,"POST",n,o);h.put=(n,o)=>d(h.config,"PUT",n,o);h.patch=(n,o)=>d(h.config,"PATCH",n,o);h.delete=n=>d(h.config,"DELETE",n);function x(n){let o=/^(.*?)([0-9]+)?$/,i=n.match(o),r=i?i[1]:null,s=i?i[2]:null;if(!r)return n;let c=s?parseInt(s)+1:1;return`${r}${c}`}h.instance=n=>{let o=!!n&&typeof n!="string",i=o?n:h.config,r=new f,s=typeof n=="string"?n:void 0;o||(r.baseUrl=i.baseUrl,r.beforeSendHandlers=[...i.beforeSendHandlers],r.beforeFetchSendHandlers=[...i.beforeFetchSendHandlers],r.onRequestCompleteHandlers=[...i.onRequestCompleteHandlers],r.authTokenStorage=i.authTokenStorage,r.inMemoryAuthToken=i.inMemoryAuthToken),r.authenticationKey=s||x(i.authenticationKey);let c=((t,a)=>d(r,a?"POST":"GET",t,a));return c.get=(t,a)=>d(r,"GET",t,a),c.post=(t,a)=>d(r,"POST",t,a),c.put=(t,a)=>d(r,"PUT",t,a),c.patch=(t,a)=>d(r,"PATCH",t,a),c.delete=(t,a)=>d(r,"DELETE",t,a),c.verbose=h.verbose,c.config=r,c.instance=t=>h.instance(t||r),c};var P=h;var w=(e=>(e[e.Continue100=100]="Continue100",e[e.SwitchingProtocols101=101]="SwitchingProtocols101",e[e.Processing102=102]="Processing102",e[e.OK200=200]="OK200",e[e.Created201=201]="Created201",e[e.Accepted202=202]="Accepted202",e[e.NoContent204=204]="NoContent204",e[e.ResetContent205=205]="ResetContent205",e[e.PartialContent206=206]="PartialContent206",e[e.MultipleChoices300=300]="MultipleChoices300",e[e.MovedPermanently301=301]="MovedPermanently301",e[e.Found302=302]="Found302",e[e.SeeOther303=303]="SeeOther303",e[e.NotModified304=304]="NotModified304",e[e.UseProxy305=305]="UseProxy305",e[e.TemporaryRedirect307=307]="TemporaryRedirect307",e[e.PermanentRedirect308=308]="PermanentRedirect308",e[e.BadRequest400=400]="BadRequest400",e[e.Unauthorized401=401]="Unauthorized401",e[e.PaymentRequired402=402]="PaymentRequired402",e[e.Forbidden403=403]="Forbidden403",e[e.NotFound404=404]="NotFound404",e[e.MethodNotAllowed405=405]="MethodNotAllowed405",e[e.NotAcceptable406=406]="NotAcceptable406",e[e.ProxyAuthenticationRequired407=407]="ProxyAuthenticationRequired407",e[e.RequestTimeout408=408]="RequestTimeout408",e[e.Conflict409=409]="Conflict409",e[e.Gone410=410]="Gone410",e[e.LengthRequired411=411]="LengthRequired411",e[e.PreconditionFailed412=412]="PreconditionFailed412",e[e.PayloadTooLarge413=413]="PayloadTooLarge413",e[e.URITooLong414=414]="URITooLong414",e[e.UnsupportedMediaType415=415]="UnsupportedMediaType415",e[e.RangeNotSatisfiable416=416]="RangeNotSatisfiable416",e[e.ExpectationFailed417=417]="ExpectationFailed417",e[e.ImATeapot418=418]="ImATeapot418",e[e.MisdirectedRequest421=421]="MisdirectedRequest421",e[e.UnprocessableEntity422=422]="UnprocessableEntity422",e[e.Locked423=423]="Locked423",e[e.FailedDependency424=424]="FailedDependency424",e[e.TooEarly425=425]="TooEarly425",e[e.UpgradeRequired426=426]="UpgradeRequired426",e[e.PreconditionRequired428=428]="PreconditionRequired428",e[e.TooManyRequests429=429]="TooManyRequests429",e[e.RequestHeaderFieldsTooLarge431=431]="RequestHeaderFieldsTooLarge431",e[e.UnavailableForLegalReasons451=451]="UnavailableForLegalReasons451",e[e.InternalServerError500=500]="InternalServerError500",e[e.NotImplemented501=501]="NotImplemented501",e[e.BadGateway502=502]="BadGateway502",e[e.ServiceUnavailable503=503]="ServiceUnavailable503",e[e.GatewayTimeout504=504]="GatewayTimeout504",e[e.HTTPVersionNotSupported505=505]="HTTPVersionNotSupported505",e[e.VariantAlsoNegotiates506=506]="VariantAlsoNegotiates506",e[e.InsufficientStorage507=507]="InsufficientStorage507",e[e.LoopDetected508=508]="LoopDetected508",e[e.NotExtended510=510]="NotExtended510",e[e.NetworkAuthenticationRequired511=511]="NetworkAuthenticationRequired511",e))(w||{});var te=P;typeof window<"u"&&(window.soFetch=P);export{w as HttpStatus,f as SoFetchConfig,g as SoFetchPromise,te as default}; //# sourceMappingURL=index.mjs.map