update
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
export const apiUrl: string =
|
||||
import.meta.env.VITE_API_URL ?? 'http://localhost:3001';
|
||||
|
||||
/** The API answered with an error status; `message` is safe to show. */
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions<T> {
|
||||
/** A schema from @repo/contracts; the response is checked against it. */
|
||||
schema: { parse: (data: unknown) => T };
|
||||
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
|
||||
/** Sent as JSON. */
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** Calls the API as the signed-in user (the session cookie goes along). */
|
||||
export async function api<T>(
|
||||
path: string,
|
||||
{ schema, method = 'GET', body, signal }: RequestOptions<T>,
|
||||
): Promise<T> {
|
||||
const response = await fetch(`${apiUrl}${path}`, {
|
||||
method,
|
||||
signal,
|
||||
credentials: 'include',
|
||||
headers:
|
||||
body === undefined ? undefined : { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, await readErrorMessage(response));
|
||||
}
|
||||
// 204 has no body to read.
|
||||
return schema.parse(
|
||||
response.status === 204 ? undefined : await response.json(),
|
||||
);
|
||||
}
|
||||
|
||||
/** The `schema` for routes that answer 204 with no body. */
|
||||
export const noContent = { parse: (): void => undefined };
|
||||
|
||||
// Errors come back as { statusCode, message, error }, where message is a
|
||||
// string or, for validation errors, a list of strings.
|
||||
async function readErrorMessage(response: Response): Promise<string> {
|
||||
const fallback = response.statusText || 'Something went wrong.';
|
||||
try {
|
||||
const data: unknown = await response.json();
|
||||
if (typeof data !== 'object' || data === null || !('message' in data)) {
|
||||
return fallback;
|
||||
}
|
||||
const { message } = data;
|
||||
if (typeof message === 'string') return message;
|
||||
if (Array.isArray(message)) return message.join(' ');
|
||||
return fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user