feat: creats frontend for the project
This commit is contained in:
62
frontend/src/api/client.ts
Normal file
62
frontend/src/api/client.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { ApiError } from '@family-budget/shared';
|
||||
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
|
||||
export function setOnUnauthorized(cb: () => void) {
|
||||
onUnauthorized = cb;
|
||||
}
|
||||
|
||||
export class ApiException extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public body: ApiError,
|
||||
) {
|
||||
super(body.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
const res = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers as Record<string, string>),
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
onUnauthorized?.();
|
||||
throw new ApiException(401, { error: 'UNAUTHORIZED', message: 'Сессия истекла' });
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
let body: ApiError;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {
|
||||
body = { error: 'UNKNOWN', message: res.statusText };
|
||||
}
|
||||
throw new ApiException(res.status, body);
|
||||
}
|
||||
|
||||
if (res.status === 204) return undefined as T;
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(url: string) => request<T>(url),
|
||||
|
||||
post: <T>(url: string, body?: unknown) =>
|
||||
request<T>(url, {
|
||||
method: 'POST',
|
||||
body: body != null ? JSON.stringify(body) : undefined,
|
||||
}),
|
||||
|
||||
put: <T>(url: string, body: unknown) =>
|
||||
request<T>(url, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
|
||||
patch: <T>(url: string, body: unknown) =>
|
||||
request<T>(url, { method: 'PATCH', body: JSON.stringify(body) }),
|
||||
};
|
||||
Reference in New Issue
Block a user