56 lines
1.4 KiB
TypeScript
56 lines
1.4 KiB
TypeScript
/**
|
|
* API utility functions for making requests to AeThex API
|
|
*/
|
|
|
|
export interface ApiResponse<T = any> {
|
|
data?: T
|
|
error?: string
|
|
message?: string
|
|
}
|
|
|
|
const API_BASE = process.env.NEXT_PUBLIC_API_URL || '/api'
|
|
|
|
export async function apiCall<T = any>(
|
|
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
|
|
endpoint: string,
|
|
body?: Record<string, any>
|
|
): Promise<ApiResponse<T>> {
|
|
try {
|
|
const response = await fetch(`${API_BASE}${endpoint}`, {
|
|
method,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
})
|
|
|
|
const data = await response.json()
|
|
|
|
if (!response.ok) {
|
|
return {
|
|
error: data.error || `HTTP ${response.status}`,
|
|
}
|
|
}
|
|
|
|
return {
|
|
data: data as T,
|
|
}
|
|
} catch (error) {
|
|
console.error(`API call failed: ${method} ${endpoint}`, error)
|
|
return {
|
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
}
|
|
}
|
|
}
|
|
|
|
// Convenience methods
|
|
export const api = {
|
|
get: <T = any>(endpoint: string) =>
|
|
apiCall<T>('GET', endpoint),
|
|
post: <T = any>(endpoint: string, body?: Record<string, any>) =>
|
|
apiCall<T>('POST', endpoint, body),
|
|
patch: <T = any>(endpoint: string, body?: Record<string, any>) =>
|
|
apiCall<T>('PATCH', endpoint, body),
|
|
delete: <T = any>(endpoint: string) =>
|
|
apiCall<T>('DELETE', endpoint),
|
|
}
|