Skip to content
File

Blob: src/client/lib/api.ts

typescript28 lines
1import createFetchClient from "openapi-fetch";
2import createClient from "openapi-react-query";
3 
4import 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).
8export const fetchClient = createFetchClient<paths>({
9 baseUrl: "",
10 credentials: "include",
11});
12 
13export const $api = createClient(fetchClient);
14 
15export 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 
23export 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}