File
Blob: src/client/lib/api.ts
| 1 | import createFetchClient from "openapi-fetch"; |
| 2 | import createClient from "openapi-react-query"; |
| 3 | |
| 4 | import type { paths } from "@/client/lib/openapi-types"; |
| 5 | |
| 6 | // baseUrl is empty because the generated `paths` already start with `/api/v1/` |
| 7 | // (openapi-typescript emits paths verbatim from the OpenAPI document). |
| 8 | export const fetchClient = createFetchClient<paths>({ |
| 9 | baseUrl: "", |
| 10 | credentials: "include", |
| 11 | }); |
| 12 | |
| 13 | export const $api = createClient(fetchClient); |
| 14 | |
| 15 | export function isApiError(value: unknown): value is { error: { code: string; message: string } } { |
| 16 | if (!value || typeof value !== "object") return false; |
| 17 | const err = (value as { error?: unknown }).error; |
| 18 | if (!err || typeof err !== "object") return false; |
| 19 | const obj = err as { code?: unknown; message?: unknown }; |
| 20 | return typeof obj.code === "string" && typeof obj.message === "string"; |
| 21 | } |
| 22 | |
| 23 | export function apiErrorMessage(value: unknown, fallback = "Something went wrong."): string { |
| 24 | if (isApiError(value)) return value.error.message; |
| 25 | if (value instanceof Error) return value.message; |
| 26 | return fallback; |
| 27 | } |