30 lines
977 B
TypeScript
30 lines
977 B
TypeScript
export class ApiError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public status: number
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
async function req<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
const init: RequestInit = { method, credentials: 'same-origin', headers: {} };
|
|
if (body instanceof FormData) init.body = body;
|
|
else if (body !== undefined) {
|
|
init.body = JSON.stringify(body);
|
|
(init.headers as Record<string, string>)['content-type'] = 'application/json';
|
|
}
|
|
const r = await fetch(path, init);
|
|
const j = await r.json().catch(() => ({}));
|
|
if (!r.ok) throw new ApiError(j?.error ?? `Ошибка ${r.status}`, r.status);
|
|
return j as T;
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(p: string) => req<T>('GET', p),
|
|
post: <T>(p: string, b?: unknown) => req<T>('POST', p, b ?? {}),
|
|
patch: <T>(p: string, b?: unknown) => req<T>('PATCH', p, b ?? {}),
|
|
put: <T>(p: string, b?: unknown) => req<T>('PUT', p, b ?? {}),
|
|
del: <T>(p: string) => req<T>('DELETE', p)
|
|
};
|