NextNodeTemplate/frontend/lib/api.ts

51 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Утилиты для работы с 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',
};
}
}