59 lines
1.5 KiB
TypeScript
59 lines
1.5 KiB
TypeScript
import { API_BASE_URL, ENDPOINTS } from '../constants/api';
|
|
import { ApiError, HttpError } from '../types';
|
|
|
|
class ApiClient {
|
|
private baseUrl: string;
|
|
|
|
constructor(baseUrl: string) {
|
|
this.baseUrl = baseUrl;
|
|
}
|
|
|
|
private async request<T>(
|
|
endpoint: string,
|
|
options: RequestInit = {}
|
|
): Promise<T> {
|
|
const url = `${this.baseUrl}${endpoint}`;
|
|
const response = await fetch(url, {
|
|
...options,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...options.headers,
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
let message = 'Request failed';
|
|
let code: string | undefined;
|
|
try {
|
|
const body: ApiError = await response.json();
|
|
message = body.error?.message || message;
|
|
code = body.error?.code;
|
|
} catch {}
|
|
throw new HttpError(response.status, message, code);
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async get<T>(endpoint: string): Promise<T> {
|
|
return this.request<T>(endpoint);
|
|
}
|
|
|
|
async post<T>(endpoint: string, body?: unknown): Promise<T> {
|
|
return this.request<T>(endpoint, {
|
|
method: 'POST',
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
}
|
|
|
|
async delete<T>(endpoint: string): Promise<T> {
|
|
return this.request<T>(endpoint, { method: 'DELETE' });
|
|
}
|
|
|
|
async getFileUrl(fileName: string): Promise<{ data: { url: string; name: string } }> {
|
|
return this.request(`${ENDPOINTS.FILE}/${fileName}`);
|
|
}
|
|
}
|
|
|
|
export const apiClient = new ApiClient(API_BASE_URL);
|