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

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
+6 -1
View File
@@ -1 +1,6 @@
VITE_API_URL=http://localhost:3000
# Базовый URL API для fetch.
# В dev — через Vite proxy (см. vite.config.ts): оставьте пустым или укажите http://localhost:3000.
# В production через reverse proxy — оставьте ПУСТЫМ (запросы пойдут на текущий origin,
# и nginx/HAProxy пробросит /api на backend). Указание http://localhost:3000 в production
# приведёт к двойному префиксу (браузер будет ходить на localhost:3000, а не на origin).
VITE_API_URL=
+11 -3
View File
@@ -329,19 +329,27 @@ export default defineConfig(
'no-alert': 'off',
// e.target.value = '' — сброс file input (стандартный паттерн)
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['e'] }],
// Навигация после await (window.location.href → useNavigate)
'require-atomic-updates': 'off',
// async IIFE в useEffect для загрузки новости
'@typescript-eslint/no-floating-promises': 'off',
// newsId гарантированно string (проверено isNew)
'@typescript-eslint/restrict-template-expressions': 'off',
},
},
{
name: 'client/auth-context',
files: ['src/auth/AuthContext.tsx'],
rules: {
// onAuthExpired: navigate('/login') возвращает void,
// но линтер требует обработки (no-floating-promises)
'@typescript-eslint/no-floating-promises': 'off',
},
},
{
name: 'client/auth-pages',
files: ['src/pages/LoginPage.tsx', 'src/pages/RegisterPage.tsx'],
rules: {
// .then()/.catch() в цепочке — не floating promise
// .then/.catch/.finally цепочка в handleSubmit: rejection обработан,
// но no-floating-promises не распознаёт pattern (см. комментарий в файле)
'@typescript-eslint/no-floating-promises': 'off',
},
},
+13 -3
View File
@@ -1,6 +1,6 @@
/**
* API-клиент: fetch-обёртка с автоматическим Authorization header
* и обработкой 401 (logout при истёкшем токене).
* и обработкой 401 (событие 'auth:expired' для AuthContext).
*/
/**
@@ -68,6 +68,17 @@ function buildHeaders(extra?: Record<string, string>): Record<string, string> {
return headers;
}
/**
* Обработка истёкшего токена (401): очищаем токен и уведомляем AuthContext.
*
* AuthContext подписывается на событие 'auth:expired' и сам делает logout
* + navigate — здесь мы не трогам роутер (client.ts не знает про React).
*/
function handleUnauthorized(): void {
setAuthToken(null);
window.dispatchEvent(new Event('auth:expired'));
}
/**
* Обрабатывает ответ: при 401 очищает токен, при !ok бросает ApiClientError.
*
@@ -76,8 +87,7 @@ function buildHeaders(extra?: Record<string, string>): Record<string, string> {
*/
async function handleResponse<T>(res: Response): Promise<T> {
if (res.status === 401 && authToken !== null) {
setAuthToken(null);
window.location.href = '/login';
handleUnauthorized();
}
const data = (await res.json().catch(() => ({}))) as unknown as ApiErrorBody & T;
+2 -2
View File
@@ -24,9 +24,9 @@ export interface NewsItem {
updatedAt: string;
}
/** Ответ на upload. */
/** Ответ на upload (сервер возвращает { file: { name, url } }). */
export interface UploadResponse {
file: { url: string; filename: string; size: number };
file: { name: string; url: string };
}
/** Тип уведомления. */
+28 -2
View File
@@ -1,4 +1,5 @@
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiFetch, setAuthToken } from '../api/client.js';
@@ -27,12 +28,19 @@ interface AuthContextValue {
logout: () => void;
}
/**
* Имя события об истёкшем токене (выпускается api/client.ts при 401
* и при connect_error Socket.IO с UNAUTHORIZED).
*/
export const AUTH_EXPIRED_EVENT = 'auth:expired';
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
/**
* Провайдер авторизации. Хранит token/userId в состоянии + localStorage.
*/
export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
const navigate = useNavigate();
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
const [userId, setUserId] = useState<string | null>(() => localStorage.getItem('userId'));
const [userEmail, setUserEmail] = useState<string | null>(() => localStorage.getItem('userEmail'));
@@ -62,15 +70,33 @@ export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
handleAuth(res);
}, [handleAuth]);
const logout = useCallback(() => {
/**
* Logout: очистка токена/данных пользователя.
* @returns void — вызывается fire-and-forget (navigate после logout)
*/
const logout = useCallback((): void => {
setAuthToken(null);
setToken(null);
setUserId(null);
setUserEmail(null);
localStorage.removeItem('userId');
localStorage.removeItem('userEmail');
// navigate('/login') вызывается вызывающей стороной (onAuthExpired)
}, []);
// При 401 (истёкший токен) — logout + редирект на /login.
// Событие выпускается api/client.ts и useSocket.ts.
useEffect(() => {
const onAuthExpired = (): void => {
logout();
navigate('/login');
};
window.addEventListener(AUTH_EXPIRED_EVENT, onAuthExpired);
return () => {
window.removeEventListener(AUTH_EXPIRED_EVENT, onAuthExpired);
};
}, [logout, navigate]);
const value = useMemo<AuthContextValue>(() => ({
token,
userId,
+3 -17
View File
@@ -1,27 +1,13 @@
import { useState } from 'react';
import { useNotifications } from '../hooks/useNotifications.js';
import { formatDateTime } from '../utils/formatDate.js';
import styles from './NotificationBell.module.scss';
import type { NotificationItem } from '../api/types.js';
/**
* Форматирует дату в коротком формате.
*
* @param iso — ISO-дата
* @returns строка вида "16.08 12:30"
*/
function formatDateTime(iso: string): string {
const d = new Date(iso);
const day = String(d.getDate()).padStart(2, '0');
const month = String(d.getMonth() + 1).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
return `${day}.${month} ${hours}:${minutes}`;
}
/**
* Одиночное уведомление в списке.
*/
@@ -60,11 +46,11 @@ export function NotificationBell({ token }: { readonly token: string | null }) {
} = useNotifications(token);
const handleMarkAsRead = (id: string): void => {
markAsRead(id).catch(() => { /* ignore */ });
void markAsRead(id).catch(() => { /* ignore */ });
};
const handleMarkAll = (): void => {
markAllAsRead().catch(() => { /* ignore */ });
void markAllAsRead().catch(() => { /* ignore */ });
};
if (token === null) {
+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);
};
+8 -3
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { apiFetch } from '../api/client.js';
import { formatDateTime } from '../utils/formatDate.js';
import styles from './NewsListPage.module.scss';
@@ -17,16 +18,20 @@ export function NewsListPage() {
const [error, setError] = useState('');
useEffect(() => {
void (async () => {
/** Загружает список новостей. */
async function loadNews(): Promise<void> {
try {
const data = await apiFetch<{ news: NewsItem[] }>('/news');
setNews(data.news);
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка загрузки');
// При 401 api-клиент уже очистил токен и выпустил auth:expired —
// AuthContext сделает logout + navigate('/login')
} finally {
setLoading(false);
}
})();
}
loadNews().catch(() => { /* ошибки обработаны внутри loadNews */ });
}, []);
if (loading) {
@@ -63,7 +68,7 @@ export function NewsListPage() {
<div className={styles.cardMeta}>
<span className={`${styles.badge} ${styles[item.status]}`}>{item.status}</span>
<span className={styles.cardDate}>
{new Date(item.updatedAt).toLocaleString('ru-RU')}
{formatDateTime(item.updatedAt)}
</span>
</div>
</li>
+14
View File
@@ -0,0 +1,14 @@
/**
* Единый формат даты для всего клиентского приложения.
*
* @param iso — ISO-дата
* @returns строка вида "16.08 12:30" (короткий формат без года)
*/
export function formatDateTime(iso: string): string {
const d = new Date(iso);
const day = String(d.getDate()).padStart(2, '0');
const month = String(d.getMonth() + 1).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
return `${day}.${month} ${hours}:${minutes}`;
}