Compare commits

...

2 Commits

Author SHA1 Message Date
d27c4a0946 Merge dev: Fix example component API endpoint
Some checks are pending
CI/CD / lint-and-build (push) Waiting to run
2025-11-02 17:12:45 +03:00
a0d2fe235e fix: Correct example component to use /api/example/data endpoint with proper validation
Some checks are pending
CI/CD / lint-and-build (push) Waiting to run
2025-11-02 17:12:42 +03:00
2 changed files with 28 additions and 8 deletions

View File

@ -20,18 +20,30 @@ export default function ExampleComponent() {
setError(null); setError(null);
try { try {
const response = await apiRequest<ApiData>('example', { // Используем правильный endpoint с валидацией: /api/example/data
const response = await apiRequest<ApiData>('example/data', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
name: 'Test', name: 'Test',
value: '123', value: 123, // Число, а не строка (валидатор требует numeric)
}), }),
}); });
if (response.success && response.data) { if (response.success && response.data) {
setData(response.data); setData({
name: response.data.name,
value: String(response.data.value), // Преобразуем для отображения
});
} else { } else {
setError(response.error || 'Unknown error'); // Улучшенная обработка ошибок валидации
let errorMessage = response.error || 'Unknown error';
if (response.errors && Array.isArray(response.errors)) {
const validationErrors = response.errors
.map((err: { msg?: string }) => err.msg || err)
.join(', ');
errorMessage = `Ошибка валидации: ${validationErrors}`;
}
setError(errorMessage);
} }
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch data'); setError(err instanceof Error ? err.message : 'Failed to fetch data');

View File

@ -18,6 +18,7 @@ export interface ApiResponse<T = unknown> {
success: boolean; success: boolean;
data?: T; data?: T;
error?: string; error?: string;
errors?: Array<{ msg?: string; param?: string }>; // Ошибки валидации
} }
export async function apiRequest<T = unknown>( export async function apiRequest<T = unknown>(
@ -33,11 +34,18 @@ export async function apiRequest<T = unknown>(
}, },
}); });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json(); const data = await response.json();
// Если статус не успешный, возвращаем данные с ошибкой
// (могут содержать детали валидации)
if (!response.ok) {
return {
success: false,
error: data.error || `HTTP error! status: ${response.status}`,
errors: data.errors, // Ошибки валидации, если есть
};
}
return data; return data;
} catch (err) { } catch (err) {
console.error('API Error:', err); console.error('API Error:', err);