45 lines
No EOL
1 KiB
TypeScript
45 lines
No EOL
1 KiB
TypeScript
const api = {
|
|
baseURL: 'http://localhost:8000/api/',
|
|
|
|
async request<T>(endpoint: string, method: string = 'GET', data: any = null): Promise<T> {
|
|
const url = `${this.baseURL}${endpoint}`;
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
const config: RequestInit = {
|
|
method,
|
|
headers,
|
|
};
|
|
|
|
if (data) {
|
|
config.body = JSON.stringify(data);
|
|
}
|
|
|
|
const response = await fetch(url, config);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
return response.json();
|
|
},
|
|
|
|
get<T>(endpoint: string): Promise<T> {
|
|
return this.request<T>(endpoint, 'GET');
|
|
},
|
|
|
|
post<T>(endpoint: string, data: any): Promise<T> {
|
|
return this.request<T>(endpoint, 'POST', data);
|
|
},
|
|
|
|
put<T>(endpoint: string, data: any): Promise<T> {
|
|
return this.request<T>(endpoint, 'PUT', data);
|
|
},
|
|
|
|
delete<T>(endpoint: string): Promise<T> {
|
|
return this.request<T>(endpoint, 'DELETE');
|
|
},
|
|
};
|
|
|
|
export default api; |