51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
// Утилиты для работы с API
|
||
|
||
const getApiUrl = (): string => {
|
||
if (typeof window === 'undefined') {
|
||
// SSR
|
||
return process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||
}
|
||
|
||
const isLocalhost = window.location.hostname === 'localhost';
|
||
return isLocalhost
|
||
? 'http://localhost:3001'
|
||
: process.env.NEXT_PUBLIC_API_URL || 'https://your-api-domain.com';
|
||
};
|
||
|
||
export const apiUrl = getApiUrl();
|
||
|
||
export interface ApiResponse<T = unknown> {
|
||
success: boolean;
|
||
data?: T;
|
||
error?: string;
|
||
}
|
||
|
||
export async function apiRequest<T = unknown>(
|
||
endpoint: string,
|
||
options: RequestInit = {}
|
||
): Promise<ApiResponse<T>> {
|
||
try {
|
||
const response = await fetch(`${apiUrl}/api/${endpoint}`, {
|
||
...options,
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
...options.headers,
|
||
},
|
||
});
|
||
|
||
if (!response.ok) {
|
||
throw new Error(`HTTP error! status: ${response.status}`);
|
||
}
|
||
|
||
const data = await response.json();
|
||
return data;
|
||
} catch (err) {
|
||
console.error('API Error:', err);
|
||
return {
|
||
success: false,
|
||
error: err instanceof Error ? err.message : 'Unknown error',
|
||
};
|
||
}
|
||
}
|
||
|