54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
// webapp/lib/api.ts
|
|
|
|
export const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000';
|
|
|
|
type ApiRequestOptions = {
|
|
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
body?: any;
|
|
token?: string | null;
|
|
wantsJson?: boolean; // Add this to control response parsing
|
|
};
|
|
|
|
export const apiRequest = async (endpoint: string, options: ApiRequestOptions = {}) => {
|
|
// Set wantsJson to true by default, false for specific cases like file streams
|
|
const { method = 'GET', body = null, token = null, wantsJson = true } = options;
|
|
|
|
const headers: HeadersInit = {
|
|
'Accept': 'application/json',
|
|
};
|
|
|
|
// Only set Content-Type for requests with a body
|
|
if (body) {
|
|
headers['Content-Type'] = 'application/json';
|
|
}
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const config: RequestInit = {
|
|
method,
|
|
headers,
|
|
};
|
|
|
|
if (body) {
|
|
config.body = JSON.stringify(body);
|
|
}
|
|
|
|
const response = await fetch(`${API_URL}${endpoint}`, config);
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json().catch(() => ({ detail: 'An unknown error occurred' }));
|
|
throw new Error(errorData.detail || `HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
if (wantsJson) {
|
|
const contentType = response.headers.get("content-type");
|
|
if (contentType?.includes("application/json")) {
|
|
return response.json();
|
|
}
|
|
}
|
|
|
|
// For non-JSON requests, return the raw response object
|
|
return response;
|
|
}; |