| [700e2f9] | 1 | const API_BASE_URL = "http://localhost:8080/api";
|
|---|
| 2 |
|
|---|
| 3 | export interface ApiError {
|
|---|
| 4 | message: string;
|
|---|
| 5 | }
|
|---|
| 6 |
|
|---|
| 7 | const getAuthToken = (): string | null => localStorage.getItem("token");
|
|---|
| 8 |
|
|---|
| 9 | const getHeaders = (includeContentType = false): HeadersInit => {
|
|---|
| 10 | const token = getAuthToken();
|
|---|
| 11 | const headers: HeadersInit = {};
|
|---|
| 12 |
|
|---|
| 13 | if (token) {
|
|---|
| 14 | headers.Authorization = `Bearer ${token}`;
|
|---|
| 15 | }
|
|---|
| 16 |
|
|---|
| 17 | if (includeContentType) {
|
|---|
| 18 | headers["Content-Type"] = "application/json";
|
|---|
| 19 | }
|
|---|
| 20 |
|
|---|
| 21 | return headers;
|
|---|
| 22 | };
|
|---|
| 23 |
|
|---|
| 24 | const handleResponse = async <T>(response: Response): Promise<T> => {
|
|---|
| 25 | if (!response.ok) {
|
|---|
| 26 | const error: ApiError = await response.json().catch(() => ({
|
|---|
| 27 | message: "An error occurred",
|
|---|
| 28 | }));
|
|---|
| 29 | throw new Error(error.message);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | if (response.status === 204) {
|
|---|
| 33 | return null as T;
|
|---|
| 34 | }
|
|---|
| 35 |
|
|---|
| 36 | return response.json();
|
|---|
| 37 | };
|
|---|
| 38 |
|
|---|
| 39 | export const apiClient = {
|
|---|
| 40 | get: async <T>(endpoint: string): Promise<T> => {
|
|---|
| 41 | const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|---|
| 42 | headers: getHeaders(),
|
|---|
| 43 | });
|
|---|
| 44 | return handleResponse<T>(response);
|
|---|
| 45 | },
|
|---|
| 46 |
|
|---|
| 47 | post: async <T>(endpoint: string, data?: unknown): Promise<T> => {
|
|---|
| 48 | const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|---|
| 49 | method: "POST",
|
|---|
| 50 | headers: getHeaders(!!data),
|
|---|
| 51 | body: data ? JSON.stringify(data) : undefined,
|
|---|
| 52 | });
|
|---|
| 53 | return handleResponse<T>(response);
|
|---|
| 54 | },
|
|---|
| 55 |
|
|---|
| 56 | put: async <T>(endpoint: string, data?: unknown): Promise<T> => {
|
|---|
| 57 | const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|---|
| 58 | method: "PUT",
|
|---|
| 59 | headers: getHeaders(!!data),
|
|---|
| 60 | body: data ? JSON.stringify(data) : undefined,
|
|---|
| 61 | });
|
|---|
| 62 | return handleResponse<T>(response);
|
|---|
| 63 | },
|
|---|
| 64 |
|
|---|
| 65 | delete: async <T>(endpoint: string): Promise<T> => {
|
|---|
| 66 | const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|---|
| 67 | method: "DELETE",
|
|---|
| 68 | headers: getHeaders(),
|
|---|
| 69 | });
|
|---|
| 70 | return handleResponse<T>(response);
|
|---|
| 71 | },
|
|---|
| 72 | };
|
|---|