const API_BASE_URL = 'http://localhost:8080/api';
|
|
interface ApiResponse<T = any> {
|
code: number;
|
message: string;
|
data: T;
|
}
|
|
class ApiService {
|
private static getToken(): string | null {
|
if (typeof window !== 'undefined') {
|
return localStorage.getItem('token');
|
}
|
return null;
|
}
|
|
static setToken(token: string): void {
|
if (typeof window !== 'undefined') {
|
localStorage.setItem('token', token);
|
}
|
}
|
|
private static async fetchWithToken(url: string, options: RequestInit = {}, customToken?: string): Promise<ApiResponse> {
|
const token = customToken || this.getToken();
|
const headers = {
|
'Content-Type': 'application/json',
|
...(token ? { 'token': token } : {}),
|
...options.headers,
|
};
|
|
const response = await fetch(`${API_BASE_URL}${url}`, {
|
...options,
|
headers,
|
});
|
|
const data = await response.json();
|
return data;
|
}
|
|
static async get<T>(url: string, customToken?: string): Promise<ApiResponse<T>> {
|
return this.fetchWithToken(url, { method: 'GET' }, customToken);
|
}
|
|
static async post<T>(url: string, body: any, customToken?: string): Promise<ApiResponse<T>> {
|
return this.fetchWithToken(url, {
|
method: 'POST',
|
body: JSON.stringify(body),
|
}, customToken);
|
}
|
|
static async put<T>(url: string, body: any, customToken?: string): Promise<ApiResponse<T>> {
|
return this.fetchWithToken(url, {
|
method: 'PUT',
|
body: JSON.stringify(body),
|
}, customToken);
|
}
|
|
static async delete<T>(url: string, customToken?: string): Promise<ApiResponse<T>> {
|
return this.fetchWithToken(url, { method: 'DELETE' }, customToken);
|
}
|
}
|
|
export default ApiService;
|