function w(o){return typeof o=="object"&&o!==null&&Object.prototype.hasOwnProperty.call(o,"data")&&Object.prototype.hasOwnProperty.call(o,"error")}function h(o){return o instanceof DOMException&&o.name==="AbortError"?new Error("api.error.timeouterror"):o instanceof TypeError&&o.message==="Failed to fetch"?new Error("api.error.connectionerror"):o instanceof Error?o:new Error(String(o))}class y{apiUrl;localStorage;constructor(r){this.apiUrl=r,this.localStorage=window.localStorage}async request(r,e,t,s=7e3,n=!1){const c={"Cache-Control":"no-cache"};if(n||(c["Content-Type"]="application/json"),this.localStorage){const a=this.localStorage.getItem("Auth-Token");a&&(c["Auth-Token"]=a)}const u=new AbortController,f=setTimeout(()=>u.abort(),s),l={method:r,cache:"no-store",mode:"cors",credentials:"include",headers:c,signal:u.signal};n?l.body=t:t!=null&&(l.body=JSON.stringify(t));try{const a=await fetch(e,l);if(!a.ok)throw new Error("api.error."+a.statusText);if(this.localStorage){const p=a.headers.get("Auth-Token");p&&this.localStorage.setItem("Auth-Token",p)}const i=await a.json();if(!w(i))throw new Error("api.error.wrongdatatype");if(i.error)throw new Error(i.error);return i}catch(a){throw h(a)}finally{clearTimeout(f)}}processResult(r){return typeof r.data!="object"?{data:r.data,error:null}:(r.data||(r.data={}),{data:r.data,error:null})}processError(r){const e=h(r);return e.message==="api.error.timeouterror"?(Object.defineProperty(e,"__api_error__",{value:e.message,writable:!1}),{data:null,error:e.message}):e.message==="api.error.connectionerror"?(Object.defineProperty(e,"__api_error__",{value:e.message,writable:!1}),{data:null,error:e.message}):{data:null,error:e.message}}async POST(r,e,t){try{const s=r.includes("/upload/"),n=await this.request("POST",this.apiUrl+r,e,t,s);return this.processResult(n)}catch(s){return this.processError(s)}}async PUT(r,e,t){try{const s=r.includes("/upload/"),n=await this.request("PUT",this.apiUrl+r,e,t,s);return this.processResult(n)}catch(s){return this.processError(s)}}async GET(r,e){try{const t=await this.request("GET",this.apiUrl+r,null,e);return this.processResult(t)}catch(t){return this.processError(t)}}async DELETE(r,e){try{const t=await this.request("DELETE",this.apiUrl+r,null,e);return this.processResult(t)}catch(t){return this.processError(t)}}async UPLOAD(r,e,t){try{const s=await this.request("POST",this.apiUrl+r,e,t,!0);return this.processResult(s)}catch(s){return this.processError(s)}}}const E=new y("http://localhost:3000");export{E as a};
