55 lines
1.2 KiB
Cheetah
55 lines
1.2 KiB
Cheetah
// Base API client configuration
|
|
{{range .AST.Definitions}}{{if .Server}}const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://{{.Server.Settings | getHost}}:{{.Server.Settings | getPort}}';
|
|
{{end}}{{end}}
|
|
|
|
export interface ApiError {
|
|
message: string;
|
|
status: number;
|
|
}
|
|
|
|
export class ApiError extends Error {
|
|
status: number;
|
|
|
|
constructor(message: string, status: number) {
|
|
super(message);
|
|
this.status = status;
|
|
this.name = 'ApiError';
|
|
}
|
|
}
|
|
|
|
export async function apiRequest<T>(
|
|
method: string,
|
|
endpoint: string,
|
|
data?: any
|
|
): Promise<T> {
|
|
const config: RequestInit = {
|
|
method,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
};
|
|
|
|
if (data) {
|
|
config.body = JSON.stringify(data);
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${API_BASE_URL}${endpoint}`, config);
|
|
|
|
if (!response.ok) {
|
|
throw new ApiError(`HTTP error! status: ${response.status}`, response.status);
|
|
}
|
|
|
|
if (response.status === 204) {
|
|
return null as T;
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
if (error instanceof ApiError) {
|
|
throw error;
|
|
}
|
|
throw new ApiError(`Network error: ${error instanceof Error ? error.message : 'Unknown error'}`, 0);
|
|
}
|
|
}
|