88 lines
2.1 KiB
TypeScript
88 lines
2.1 KiB
TypeScript
const API_URL = process.env.NEXT_PUBLIC_API_URL || '';
|
|
|
|
class ApiClient {
|
|
private baseUrl: string;
|
|
|
|
constructor(baseUrl: string = '') {
|
|
this.baseUrl = baseUrl;
|
|
}
|
|
|
|
async get(path: string, params?: Record<string, any>): Promise<any> {
|
|
const url = new URL(path, this.baseUrl || window.location.origin);
|
|
if (params) {
|
|
Object.entries(params).forEach(([key, value]) => {
|
|
if (value !== undefined && value !== null && value !== '') {
|
|
url.searchParams.append(key, String(value));
|
|
}
|
|
});
|
|
}
|
|
|
|
const response = await fetch(url.toString(), {
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`API error: ${response.status}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async post(path: string, data: any): Promise<any> {
|
|
const url = new URL(path, this.baseUrl || window.location.origin);
|
|
|
|
const response = await fetch(url.toString(), {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(data),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`API error: ${response.status}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async put(path: string, data?: any): Promise<any> {
|
|
const url = new URL(path, this.baseUrl || window.location.origin);
|
|
|
|
const response = await fetch(url.toString(), {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: data ? JSON.stringify(data) : undefined,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`API error: ${response.status}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async delete(path: string): Promise<any> {
|
|
const url = new URL(path, this.baseUrl || window.location.origin);
|
|
|
|
const response = await fetch(url.toString(), {
|
|
method: 'DELETE',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`API error: ${response.status}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
}
|
|
|
|
export const api = new ApiClient(API_URL);
|