siegel
Version:
Web application development ecosystem
1 lines • 2.36 kB
JavaScript
import e from"../../../common/populate_url_params/index.js";import t from"../../../common/is/exists/index.js";let r="content-type",a="application/json",s={[r]:a},o="json";async function n(e,t){let s,{jsonParsePreprocess:n}=e,{parseMethod:i}=e;!i&&(i="text",(s=t.headers.get(r))&&(s.startsWith(a)?i=o:(s.startsWith("multipart/form-data")||s.startsWith("application/x-www-form-urlencoded"))&&(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.`,{cause:e})}}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:c,beforeParse:d,beforeRequest:h,afterRequest:f,errorHandler:p,json:u,jsonParsePreprocess:y,jsonStringifyPostprocess:m}=o,w=new Set;return async o=>{t(o.json)||(o.json=u),o.jsonStringifyPostprocess||=m,o.jsonParsePreprocess||=y,o.fetchOptionsPostprocess||=c;let S=d?.(o);S&&await S.then(e=>{o=e});let g=function(t){let{url:o,query:n,params:i,method:l,headers:c,body:d,credentials:h,signal:f,json:p,passThroughPayload:u,jsonStringifyPostprocess:y,fetchOptionsPostprocess:m}=t,w={method:l};d&&(w.body=d,w.method||="POST"),w.method||="GET";let S=i?e(o,i):o;if(n){let e;if("string"==typeof n)e=n;else if(n instanceof URLSearchParams)e=n.toString();else{let t=new URLSearchParams;Object.keys(n).forEach(e=>{let r=n[e];Array.isArray(r)?r.forEach(r=>{t.append(e,r)}):t.set(e,r)}),e=t.toString()}S+=`?${e}`}return h&&(w.credentials=h),c&&(w.headers=c),f&&(w.signal=f),p&&(w.body&&(w.body=JSON.stringify(w.body),y&&(w.body=y(w.body))),w.headers?w.headers[r]||=a:w.headers=s),m?.(w),{options:w,passThroughPayload:u,initialURL:o,url:S}}(o);if(!(await i(h,g)&&await i(o.beforeRequest,g)))return{res:null,err:null};{let e,{isFullRes:t,preventSame:r}=o,{options:a,url:s}=g,i=!1!=r&&(r||l);i&&(e=`${s}_${a.method}_${a.body}`);try{if(i)if(w.has(e))throw{err:Error("Same request is already processing..."),canceled:!0};else w.add(e);let r=await fetch(s,a),{headers:l,status:c,statusText:d,ok:h}=r,p=await n(o,r);if(i&&w.delete(e),t&&(p={status:c,statusText:d,headers:l,data:p}),h)return f?.(g,p),o.onSuccess?.(p),{res:p,err:null};throw{status:c,message:d,res:p}}catch(t){return i&&w.delete(e),t.req=g,o.onError?.(t),p?.(t),{res:null,err:t}}}}});