( url: string, options: RequestInit, )
| 37 | }; |
| 38 | |
| 39 | export const customFetch = async <T>( |
| 40 | url: string, |
| 41 | options: RequestInit, |
| 42 | ): Promise<T> => { |
| 43 | const baseUrl = getApiBaseUrl(); |
| 44 | |
| 45 | const headers = new Headers(options.headers); |
| 46 | const hasBody = options.body !== undefined && options.body !== null; |
| 47 | if (hasBody && !headers.has("Content-Type")) { |
| 48 | headers.set("Content-Type", "application/json"); |
| 49 | } |
| 50 | if (isLocalAuthMode() && !headers.has("Authorization")) { |
| 51 | const token = getLocalAuthToken(); |
| 52 | if (token) { |
| 53 | headers.set("Authorization", `Bearer ${token}`); |
| 54 | } |
| 55 | } |
| 56 | if (!headers.has("Authorization")) { |
| 57 | const token = await resolveClerkToken(); |
| 58 | if (token) { |
| 59 | headers.set("Authorization", `Bearer ${token}`); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | const response = await fetch(`${baseUrl}${url}`, { |
| 64 | ...options, |
| 65 | headers, |
| 66 | }); |
| 67 | |
| 68 | if (!response.ok) { |
| 69 | const contentType = response.headers.get("content-type") ?? ""; |
| 70 | let errorData: unknown = null; |
| 71 | const isJson = |
| 72 | contentType.includes("application/json") || contentType.includes("+json"); |
| 73 | if (isJson) { |
| 74 | errorData = (await response.json().catch(() => null)) as unknown; |
| 75 | } else { |
| 76 | errorData = await response.text().catch(() => ""); |
| 77 | } |
| 78 | |
| 79 | let message = |
| 80 | typeof errorData === "string" && errorData ? errorData : "Request failed"; |
| 81 | if (errorData && typeof errorData === "object") { |
| 82 | const detail = (errorData as { detail?: unknown }).detail; |
| 83 | if (typeof detail === "string" && detail) { |
| 84 | message = detail; |
| 85 | } else if (Array.isArray(detail) && detail.length) { |
| 86 | const first = detail[0] as { msg?: unknown }; |
| 87 | if ( |
| 88 | first && |
| 89 | typeof first === "object" && |
| 90 | typeof first.msg === "string" |
| 91 | ) { |
| 92 | message = first.msg; |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | throw new ApiError(response.status, message, errorData); |
no test coverage detected