48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
// We still export this for use in components where the raw URL is needed,
|
|
// like the <video> src attribute.
|
|
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;
|
|
};
|
|
|
|
export const apiRequest = async (endpoint: string, options: ApiRequestOptions = {}) => {
|
|
const { method = 'GET', body = null, token = null } = options;
|
|
|
|
const headers: HeadersInit = {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
};
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const config: RequestInit = {
|
|
method,
|
|
headers,
|
|
};
|
|
|
|
if (body) {
|
|
config.body = JSON.stringify(body);
|
|
}
|
|
|
|
// Use the API_URL variable to construct the full URL inside the function
|
|
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}`);
|
|
}
|
|
|
|
// Handle cases where the response might not be JSON
|
|
const contentType = response.headers.get("content-type");
|
|
if (contentType?.includes("application/json")) {
|
|
return response.json();
|
|
}
|
|
|
|
// For non-json responses (like video streams or simple text), return the raw response
|
|
return response;
|
|
}; |