typizator-client
Version:
Client library for a generic server API creator with typizator and cdk-typescript-lib
2 lines (1 loc) • 1.61 kB
JavaScript
import f from"json-bigint";var T="ApiUrl",A=r=>r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),h=(r,e,s)=>{if(r.hidden)return{};let l=e.url.endsWith("/")?e.url:`${e.url}/`,d={};return Object.keys(r.implementation).forEach(n=>{let a=r.implementation[n].metadata,p=A(n);if(a.dataType==="api"){let t=e.children?.[n];d[n]=h(a,{url:t?.url??l,path:`${e.path?`${e.path}/`:""}${p}`,children:t?.children,freeze:t?.freeze??e.freeze,unfreeze:t?.unfreeze??e.unfreeze,wildcardCors:t?.wildcardCors??e.wildcardCors},s)}else{if(a.hidden)return;let t=`${l}${e.path?`${e.path}/`:""}${p}`;d[n]=async(...m)=>{e.freeze?.();let u=!navigator||/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=await fetch(t,{method:"POST",credentials:e.wildcardCors?void 0:u?"same-origin":"include",headers:{Accept:"application/json","Content-Type":"application/json","x-security-token":s?.()??"",Origin:window.location.origin,"X-Requested-With":"XMLHttpRequest","X-Custom-Header":"1",Authorization:"Bearer rand"},body:f.stringify(m)}).then(o=>o.status===401?{errorMessage:"Unauthorized"}:o.json()).catch(o=>{throw new Error(`Error in fetch: ${o.message}`)}).finally(()=>e.unfreeze?.());if(i?.errorMessage)throw new Error(`Server error: ${i.errorMessage}`);if(i?.message)throw new Error(`Server error: ${i.message}`);if(a.retVal){if(i?.data===void 0)throw new Error(`There must be a data field in the received JSON: ${f.stringify(i)}`);return typeof i.data=="string"&&i.data.startsWith('"')?a.retVal?.unbox(i.data.substring(1,i.data.length-1)):a.retVal?.unbox(i.data)}}}}),d},c=(r,e,s)=>h(r,e,s);export{T as API_URL_PARAM,c as connectTsApi};