Ревью кода: исправление найденных проблем

This commit is contained in:
Suslov-MD
2026-08-16 18:49:14 +00:00
parent dad4642197
commit 29b0a16f94
28 changed files with 726 additions and 396 deletions
+75 -93
View File
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiFetch, apiUpload } from '../api/client.js';
@@ -50,6 +51,29 @@ export function useNewsEditor(newsId: string | undefined) {
const [error, setError] = useState('');
const [scheduleDate, setScheduleDate] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
const navigate = useNavigate();
/**
* Общий хелпер для CRUD-действий: saving-флаг, сброс/установка error, catch.
* Навигация (если нужна) выполняется внутри action.
*
* @param action — асинхронная операция
* @param fallbackMessage — сообщение об ошибке по умолчанию
*/
const runAction = useCallback(
(action: () => Promise<void>, fallbackMessage: string): void => {
setSaving(true);
setError('');
void action()
.catch((err: unknown) => {
setError(err instanceof Error ? err.message : fallbackMessage);
})
.finally(() => {
setSaving(false);
});
},
[],
);
/** Вставляет markdown-фрагмент в textarea на позиции курсора. */
const insertMarkdown = useCallback((before: string, after = ''): void => {
@@ -69,97 +93,72 @@ export function useNewsEditor(newsId: string | undefined) {
});
}, [content, setContent]);
/** Сохраняет черновик. */
const handleSave = useCallback(async (): Promise<void> => {
setSaving(true);
setError('');
try {
/** Сохраняет черновик. Новая новость → переход на /news. */
const onSave = useCallback((): void => {
runAction(async () => {
if (isNew) {
await apiFetch('/news', {
method: 'POST',
body: JSON.stringify({ title, content }),
});
window.location.href = '/news';
} else {
await apiFetch(`/news/${newsId}`, {
method: 'PATCH',
body: JSON.stringify({ title, content }),
});
setError('Сохранено ✓');
setTimeout(() => { setError(''); }, 2000);
navigate('/news');
return;
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка сохранения');
} finally {
setSaving(false);
}
}, [isNew, newsId, title, content]);
await apiFetch(`/news/${newsId}`, {
method: 'PATCH',
body: JSON.stringify({ title, content }),
});
setError('Сохранено ✓');
setTimeout(() => { setError(''); }, 2000);
}, 'Ошибка сохранения');
}, [runAction, isNew, newsId, title, content, navigate]);
/** Публикует немедленно. */
const handlePublish = useCallback(async (): Promise<void> => {
if (newsId === undefined) {
setError('Сначала сохраните черновик');
return;
}
setSaving(true);
setError('');
try {
const onPublish = useCallback((): void => {
runAction(async () => {
if (newsId === undefined) {
setError('Сначала сохраните черновик');
return;
}
await apiFetch(`/news/${newsId}/publish`, { method: 'POST' });
window.location.href = '/news';
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка публикации');
} finally {
setSaving(false);
}
}, [newsId]);
navigate('/news');
}, 'Ошибка публикации');
}, [runAction, newsId, navigate]);
/** Планирует публикацию. */
const handleSchedule = useCallback(async (): Promise<void> => {
if (newsId === undefined) {
setError('Сначала сохраните черновик');
return;
}
if (scheduleDate === '') {
setError('Выберите дату публикации');
return;
}
setSaving(true);
setError('');
try {
const onSchedule = useCallback((): void => {
runAction(async () => {
if (newsId === undefined) {
setError('Сначала сохраните черновик');
return;
}
if (scheduleDate === '') {
setError('Выберите дату публикации');
return;
}
// datetime-local даёт local time — конвертируем в ISO (UTC) для сервера
const iso = new Date(scheduleDate).toISOString();
await apiFetch(`/news/${newsId}/schedule`, {
method: 'POST',
body: JSON.stringify({ scheduledAt: scheduleDate }),
body: JSON.stringify({ scheduledAt: iso }),
});
window.location.href = '/news';
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка планирования');
} finally {
setSaving(false);
}
}, [newsId, scheduleDate]);
navigate('/news');
}, 'Ошибка планирования');
}, [runAction, newsId, scheduleDate, navigate]);
/** Удаляет новость. */
const handleDelete = useCallback(async (): Promise<void> => {
if (newsId === undefined) {
return;
}
if (!window.confirm('Удалить новость?')) {
return;
}
setSaving(true);
setError('');
try {
const onDelete = useCallback((): void => {
runAction(async () => {
if (newsId === undefined) {
return;
}
if (!window.confirm('Удалить новость?')) {
return;
}
await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
window.location.href = '/news';
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка удаления');
} finally {
setSaving(false);
}
}, [newsId]);
navigate('/news');
}, 'Ошибка удаления');
}, [runAction, newsId, navigate]);
/** Загружает файл и вставляет markdown-ссылку. */
const handleFileUpload = useCallback(async (file: File, isImage: boolean): Promise<void> => {
@@ -176,23 +175,6 @@ export function useNewsEditor(newsId: string | undefined) {
}
}, [insertMarkdown]);
// Обёртки для onClick: .catch() чтобы не триггерить no-floating-promises
const onSave = useCallback((): void => {
handleSave().catch((e: unknown) => { console.error('Save failed', e); });
}, [handleSave]);
const onPublish = useCallback((): void => {
handlePublish().catch((e: unknown) => { console.error('Publish failed', e); });
}, [handlePublish]);
const onDelete = useCallback((): void => {
handleDelete().catch((e: unknown) => { console.error('Delete failed', e); });
}, [handleDelete]);
const onSchedule = useCallback((): void => {
handleSchedule().catch((e: unknown) => { console.error('Schedule failed', e); });
}, [handleSchedule]);
/** Обработчик toolbar-кнопок. */
const handleToolbarAction = useCallback((action: string): void => {
if (action === 'bold') { insertMarkdown('**', '**'); }
@@ -207,7 +189,7 @@ export function useNewsEditor(newsId: string | undefined) {
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
void handleFileUpload(file, true);
}
e.target.value = '';
}, [handleFileUpload]);
@@ -216,7 +198,7 @@ export function useNewsEditor(newsId: string | undefined) {
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
void handleFileUpload(file, false);
}
e.target.value = '';
}, [handleFileUpload]);
+7 -6
View File
@@ -29,8 +29,9 @@ export function useNotifications(token: string | null) {
]);
setNotifications(listRes.notifications);
setUnreadCount(countRes.count);
} catch {
// Ошибка загрузки — игнорируем (user может быть offline)
} catch (err) {
// Ошибка загрузки — логируем, user может быть offline
console.error('Не удалось загрузить уведомления:', err);
}
}, []);
@@ -40,8 +41,8 @@ export function useNotifications(token: string | null) {
await apiFetch(`/notifications/${id}/read`, { method: 'PATCH' });
setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, isRead: true } : n));
setUnreadCount((prev) => Math.max(0, prev - 1));
} catch {
// Игнорируем ошибку
} catch (err) {
console.error('Не удалось отметить уведомление прочитанным:', err);
}
}, []);
@@ -51,8 +52,8 @@ export function useNotifications(token: string | null) {
await apiFetch('/notifications/read-all', { method: 'POST' });
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
setUnreadCount(0);
} catch {
// Игнорируем ошибку
} catch (err) {
console.error('Не удалось отметить все уведомления прочитанными:', err);
}
}, []);
+21
View File
@@ -1,9 +1,15 @@
import { useEffect, useState } from 'react';
import { io, type Socket } from 'socket.io-client';
import { AUTH_EXPIRED_EVENT } from '../auth/AuthContext.js';
/**
* Подключается к Socket.IO серверу с JWT-аутентификацией.
*
* При connect_error с UNAUTHORIZED (истёкший/невалидный JWT) — выпускает
* событие 'auth:expired': AuthContext делает logout + navigate.
* Это прерывает бесконечный reconnect loop с мёртвым токеном.
*
* @param token — JWT токен пользователя
* @param url — URL Socket.IO сервера (по умолчанию — текущий origin)
* @returns socket или null (если не подключено)
@@ -23,9 +29,24 @@ export function useSocket(token: string | null, url?: string): Socket | null {
transports: ['websocket', 'polling'],
});
// UNAUTHORIZED на handshake — не ререконнектимся бесконечно:
// логируем, отключаем и уведомляем AuthContext.
const onConnectError = (err: Error): void => {
const isUnauthorized =
err.message.includes('UNAUTHORIZED') || err.message.includes('недействительный токен');
if (!isUnauthorized) {
return;
}
console.warn('Socket.IO: токен недействителен, разрываем соединение', err.message);
newSocket.disconnect();
window.dispatchEvent(new Event(AUTH_EXPIRED_EVENT));
};
newSocket.on('connect_error', onConnectError);
setSocket(newSocket);
return () => {
newSocket.off('connect_error', onConnectError);
newSocket.disconnect();
setSocket(null);
};