siegel
Version:
Web application development ecosystem
1 lines • 2.28 kB
JavaScript
import e from"../../../common/populate_url_params/index.js";import t from"../../../common/is/exists/index.js";let r={CONTENT_TYPE:"content-type"},a={JSON:"application/json",FORM_DATA:"multipart/form-data",X_FORM:"application/x-www-form-urlencoded"},s={[r.CONTENT_TYPE]:a.JSON},o="json";async function n(e,t){let s,{jsonParsePreprocess:n}=e,{parseMethod:i}=e;!i&&(i="text",(s=t.headers.get(r.CONTENT_TYPE))&&(s.startsWith(a.JSON)?i=o:(s.startsWith(a.FORM_DATA)||s.startsWith(a.X_FORM))&&(i="formData")));try{return n&&i==o?JSON.parse(n(await t.text())):await t[i]()}catch(e){throw Error(`${e}. Failed to parse contentType: ${s} using ${i}() method.`)}}async function i(e,r){let a=e?.(r),s=!0;return t(a)&&("object"==typeof a?await a.then(e=>{s=e}):s=a),s}export default((o={})=>{let{preventSame:l,fetchOptionsPostprocess:d,beforeParse:c,beforeRequest:h,afterRequest:u,errorHandler:p,json:m,jsonParsePreprocess:f,jsonStringifyPostprocess:y}=o,T=new Set;return async o=>{let w;t(o.json)||(o.json=m),o.jsonStringifyPostprocess||=y,o.jsonParsePreprocess||=f,o.fetchOptionsPostprocess||=d;let O=c?.(o);O&&await O.then(e=>{o=e});let{isFullRes:N,preventSame:S}=o,E=function(t){let{url:o,query:n,params:i,method:l,headers:d,body:c,credentials:h,signal:u,json:p,passThroughPayload:m,jsonStringifyPostprocess:f,fetchOptionsPostprocess:y}=t,T={method:l};c&&(T.body=c,T.method||="POST"),T.method||="GET";let w=i?e(o,i):o;return n&&(w+=n instanceof String?n:`?${new URLSearchParams(n)}`),h&&(T.credentials=h),d&&(T.headers=d),u&&(T.signal=u),p&&(T.body&&(T.body=JSON.stringify(T.body),f&&(T.body=f(T.body))),T.headers?T.headers[r.CONTENT_TYPE]||=a.JSON:T.headers=s),y?.(T),{options:T,passThroughPayload:m,initialURL:o,url:w}}(o),{options:_,url:P}=E,b=!1!=S&&(S||l);if(b&&(w=`${P}_${_.method}_${_.body}`),!(await i(h,E)&&await i(o.beforeRequest,E)))return{res:null,err:null};try{if(b)if(T.has(w))throw{err:Error("Same request is already processing..."),canceled:!0};else T.add(w);let e=await fetch(P,_),{headers:t,status:r,statusText:a,ok:s}=e,i=await n(o,e);if(b&&T.delete(w),N&&(i={status:r,statusText:a,headers:t,data:i}),s)return u?.(E,i),o.onSuccess?.(i),{res:i,err:null};throw{status:r,message:a,res:i}}catch(e){return b&&T.delete(w),e.req=E,o.onError?.(e),p?.(e),{res:null,err:e}}}});