( url: string, opts: ApiOpts, auth = true )
| 15 | } |
| 16 | |
| 17 | export async function fetchURL( |
| 18 | url: string, |
| 19 | opts: ApiOpts, |
| 20 | auth = true |
| 21 | ): Promise<Response> { |
| 22 | const authStore = useAuthStore(); |
| 23 | |
| 24 | opts = opts || {}; |
| 25 | opts.headers = opts.headers || {}; |
| 26 | |
| 27 | const { headers, ...rest } = opts; |
| 28 | let res; |
| 29 | try { |
| 30 | res = await fetch(`${baseURL}${url}`, { |
| 31 | headers: { |
| 32 | "X-Auth": authStore.jwt, |
| 33 | ...headers, |
| 34 | }, |
| 35 | ...rest, |
| 36 | }); |
| 37 | } catch (e) { |
| 38 | // Check if the error is an intentional cancellation |
| 39 | if (e instanceof Error && e.name === "AbortError") { |
| 40 | throw new StatusError("000 No connection", 0, true); |
| 41 | } |
| 42 | throw new StatusError("000 No connection", 0); |
| 43 | } |
| 44 | |
| 45 | if (auth && res.headers.get("X-Renew-Token") === "true") { |
| 46 | await renew(authStore.jwt); |
| 47 | } |
| 48 | |
| 49 | if (res.status < 200 || res.status > 299) { |
| 50 | const body = await res.text(); |
| 51 | const error = new StatusError( |
| 52 | body || `${res.status} ${res.statusText}`, |
| 53 | res.status |
| 54 | ); |
| 55 | |
| 56 | if (auth && res.status == 401) { |
| 57 | logout(); |
| 58 | } |
| 59 | |
| 60 | throw error; |
| 61 | } |
| 62 | |
| 63 | return res; |
| 64 | } |
| 65 | |
| 66 | export async function fetchJSON<T>(url: string, opts?: any): Promise<T> { |
| 67 | const res = await fetchURL(url, opts); |
no test coverage detected