feat: Phase 6+9 real-time уведомления, CSS Modules, UI-правки
This commit is contained in:
+27
-10
@@ -7,27 +7,43 @@ import { errorHandler } from './middleware/error.middleware.js';
|
||||
import { notFoundHandler } from './middleware/notFound.middleware.js';
|
||||
import authRouter from './routes/auth.routes.js';
|
||||
import healthRouter from './routes/health.routes.js';
|
||||
import newsRouter from './routes/news.routes.js';
|
||||
import { createNewsRouter } from './routes/news.routes.js';
|
||||
import notificationRouter from './routes/notification.routes.js';
|
||||
import uploadRouter from './routes/upload.routes.js';
|
||||
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Параметры для создания приложения.
|
||||
*/
|
||||
interface CreateAppOptions {
|
||||
/** Экземпляр Socket.IO server (передаётся в news routes для emit). */
|
||||
readonly io?: SocketIOServer;
|
||||
/** Дополнительные middleware (тесты). */
|
||||
readonly extraMiddleware?: express.RequestHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Express-приложение.
|
||||
*
|
||||
* Функция (а не готовый экземпляр) позволяет тестам создавать
|
||||
* независимые приложения без побочных эффектов.
|
||||
*
|
||||
* @param extraMiddleware — дополнительные middleware, подключаемые
|
||||
* после роутеров и до терминальных обработчиков (используется в тестах
|
||||
* для проверки error middleware на контролируемых путях)
|
||||
* @param options — параметры (io, extraMiddleware)
|
||||
* @returns настроенное Express-приложение
|
||||
*/
|
||||
export function createApp(extraMiddleware?: express.RequestHandler): express.Express {
|
||||
export function createApp(options?: CreateAppOptions): express.Express {
|
||||
const app = express();
|
||||
const { io, extraMiddleware } = options ?? {};
|
||||
|
||||
// /socket.io — Socket.IO (engine.io) обрабатывает на уровне HTTP server.
|
||||
// Express НЕ отвечает на эти запросы (не вызывает res.send/next).
|
||||
// Socket.IO handler (второй listener) получает те же req/res и отвечает.
|
||||
app.use('/socket.io', () => {
|
||||
// Intentionally empty — не отвечаем, Socket.IO обработает
|
||||
});
|
||||
|
||||
// Security headers
|
||||
app.use(helmet());
|
||||
|
||||
// CORS — whitelist из CLIENT_ORIGIN (поддерживается несколько через запятую)
|
||||
// CORS — whitelist из CLIENT_ORIGIN
|
||||
app.use(cors({ origin: env.clientOrigins }));
|
||||
|
||||
// Парсинг тела запроса
|
||||
@@ -41,7 +57,8 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
|
||||
// API-маршруты
|
||||
app.use('/api', healthRouter);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/news', newsRouter);
|
||||
app.use('/api/news', createNewsRouter(io));
|
||||
app.use('/api/notifications', notificationRouter);
|
||||
app.use('/api/uploads', uploadRouter);
|
||||
|
||||
// Дополнительные middleware (тестовые маршруты, заглушки)
|
||||
|
||||
@@ -25,6 +25,11 @@ function errorMessageOf(err: unknown): string {
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- сигнатура Express требует 4 аргумента
|
||||
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
||||
if (res.headersSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ожидаемая ошибка — возвращаем её статус и код
|
||||
if (err instanceof ApiError) {
|
||||
res.status(err.status).json({ error: { code: err.code, message: err.message } });
|
||||
|
||||
@@ -8,6 +8,10 @@ import type { NextFunction, Request, Response } from 'express';
|
||||
* Вызывается после всех маршрутизаторов и передаёт ошибку 404
|
||||
* в централизованный error middleware.
|
||||
*/
|
||||
export function notFoundHandler(req: Request, _res: Response, next: NextFunction): void {
|
||||
export function notFoundHandler(req: Request, res: Response, next: NextFunction): void {
|
||||
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
||||
if (res.headersSent) {
|
||||
return;
|
||||
}
|
||||
next(new ApiError(404, 'NOT_FOUND', `Маршрут не найден: ${req.method} ${req.originalUrl}`));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Schema, model, type HydratedDocument, type Types } from 'mongoose';
|
||||
|
||||
/** Тип уведомления о действиях с новостью. */
|
||||
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
|
||||
|
||||
export interface INotification {
|
||||
/** Получатель уведомления. */
|
||||
user: Types.ObjectId;
|
||||
/** Кто совершил действие (может совпадать с user). */
|
||||
actor: Types.ObjectId | null;
|
||||
/** Тип события. */
|
||||
type: NotificationType;
|
||||
/** Ссылка на новость (если применимо). */
|
||||
news: Types.ObjectId | null;
|
||||
/** Заголовок уведомления. */
|
||||
title: string;
|
||||
/** Тело сообщения. */
|
||||
message: string;
|
||||
/** Прочитано ли. */
|
||||
isRead: boolean;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export type NotificationDocument = HydratedDocument<INotification>;
|
||||
|
||||
const notificationSchema = new Schema<INotification>(
|
||||
{
|
||||
user: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
required: [true, 'Получатель уведомления обязателен'],
|
||||
},
|
||||
actor: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
default: null,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['news.created', 'news.updated', 'news.deleted', 'news.scheduled', 'news.published'],
|
||||
required: [true, 'Тип уведомления обязателен'],
|
||||
},
|
||||
news: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'News',
|
||||
default: null,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
required: [true, 'Заголовок уведомления обязателен'],
|
||||
trim: true,
|
||||
},
|
||||
message: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
isRead: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: { createdAt: true, updatedAt: false },
|
||||
},
|
||||
);
|
||||
|
||||
// Индекс для быстрого поиска непрочитанных
|
||||
notificationSchema.index({ user: 1, isRead: 1, createdAt: -1 });
|
||||
|
||||
const Notification = model<INotification>('Notification', notificationSchema);
|
||||
|
||||
export default Notification;
|
||||
@@ -2,25 +2,16 @@ import { Router, type Request, type Response } from 'express';
|
||||
|
||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
||||
import News from '../models/news.model.js';
|
||||
import { createNotification } from '../services/notification.service.js';
|
||||
import { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
const newsRouter = Router();
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
// Сообщение об авторизации
|
||||
const AUTH_MSG = 'Требуется авторизация';
|
||||
// Сообщение о не найденной новости
|
||||
const NOT_FOUND_MSG = 'Новость не найдена';
|
||||
|
||||
// Все маршруты требуют авторизацию
|
||||
newsRouter.use(requireAuth);
|
||||
|
||||
/**
|
||||
* Возвращает id авторизованного пользователя или бросает 401.
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @returns id пользователя (string)
|
||||
*/
|
||||
/** Возвращает id авторизованного пользователя. */
|
||||
function getUserId(req: Request): string {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
@@ -30,25 +21,14 @@ function getUserId(req: Request): string {
|
||||
return authedReq.user.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Безопасно извлекает поле из req.body (any → unknown).
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @param key — имя поля
|
||||
* @returns значение поля (unknown)
|
||||
*/
|
||||
/** Безопасно извлекает поле из req.body. */
|
||||
function bodyField(req: Request, key: string): unknown {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express typed as any
|
||||
const raw = (req.body ?? {}) as Record<string, unknown>;
|
||||
return raw[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирует Mongoose-документ новости для JSON-ответа.
|
||||
*
|
||||
* @param n — документ Mongoose
|
||||
* @returns объект с публичными полями
|
||||
*/
|
||||
/** Форматирует документ новости для JSON. */
|
||||
function serializeNews(n: InstanceType<typeof News>) {
|
||||
return {
|
||||
id: n._id,
|
||||
@@ -63,89 +43,58 @@ function serializeNews(n: InstanceType<typeof News>) {
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/news
|
||||
* Список новостей пользователя (все статусы).
|
||||
* Создаёт news router с привязкой к Socket.IO серверу.
|
||||
*
|
||||
* @returns 200 { news: [...] }
|
||||
* @param io — Socket.IO server для отправки real-time событий
|
||||
* @returns настроенный Router
|
||||
*/
|
||||
newsRouter.get(
|
||||
'/',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
/* eslint-disable max-lines-per-function -- factory-функция с 6 inline handlers (стандартный Express-паттерн) */
|
||||
export function createNewsRouter(io?: SocketIOServer): Router {
|
||||
const router = Router();
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const items = await News.find({ author: userId }).sort({ createdAt: -1 });
|
||||
|
||||
res.json({ news: items.map(serializeNews) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* GET /api/news/:id
|
||||
* Одна новость. Ownership: только свои статьи.
|
||||
*
|
||||
* @returns 200 { news: { id, title, content, status, ... } }
|
||||
*/
|
||||
newsRouter.get(
|
||||
'/:id',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.get('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/news
|
||||
* Создаёт новость (draft).
|
||||
*
|
||||
* @returns 201 { news: { id, title, content, status, ... } }
|
||||
*/
|
||||
newsRouter.post(
|
||||
'/',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.post('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const title = bodyField(req, 'title');
|
||||
const content = bodyField(req, 'content');
|
||||
|
||||
if (typeof title !== 'string' || title.trim().length === 0) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
|
||||
}
|
||||
if (title.trim().length > 200) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов');
|
||||
}
|
||||
|
||||
const news = await News.create({
|
||||
title: title.trim(),
|
||||
content: typeof content === 'string' ? content : '',
|
||||
status: 'draft',
|
||||
author: userId,
|
||||
});
|
||||
|
||||
res.status(201).json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* PATCH /api/news/:id
|
||||
* Обновляет title и/или content. Ownership: только свои статьи.
|
||||
*
|
||||
* @returns 200 { news: { id, title, content, status, ... } }
|
||||
*/
|
||||
newsRouter.patch(
|
||||
'/:id',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
const title = bodyField(req, 'title');
|
||||
const content = bodyField(req, 'content');
|
||||
|
||||
if (title !== undefined) {
|
||||
if (typeof title !== 'string' || title.trim().length === 0) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
|
||||
@@ -155,93 +104,72 @@ newsRouter.patch(
|
||||
}
|
||||
news.title = title.trim();
|
||||
}
|
||||
|
||||
if (content !== undefined) {
|
||||
if (typeof content !== 'string') {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Контент должен быть строкой');
|
||||
}
|
||||
news.content = content;
|
||||
}
|
||||
|
||||
await news.save();
|
||||
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* DELETE /api/news/:id
|
||||
* Удаляет новость. Ownership: только свои статьи.
|
||||
*
|
||||
* @returns 204
|
||||
*/
|
||||
newsRouter.delete(
|
||||
'/:id',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
const title = news.title;
|
||||
await news.deleteOne();
|
||||
if (io) {
|
||||
await createNotification(io, {
|
||||
user: userId, actor: userId, type: 'news.deleted',
|
||||
newsId: String(req.params.id),
|
||||
title: 'Новость удалена',
|
||||
message: `«${title}» была удалена`,
|
||||
});
|
||||
}
|
||||
res.status(204).send();
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/news/:id/publish
|
||||
* Немедленная публикация новости.
|
||||
*
|
||||
* @returns 200 { news: { id, title, content, status: 'published', ... } }
|
||||
*/
|
||||
newsRouter.post(
|
||||
'/:id/publish',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.post('/:id/publish', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
if (news.status === 'published') {
|
||||
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
||||
}
|
||||
|
||||
news.status = 'published';
|
||||
news.publishedAt = new Date();
|
||||
news.scheduledAt = null;
|
||||
await news.save();
|
||||
|
||||
if (io) {
|
||||
await createNotification(io, {
|
||||
user: userId, actor: userId, type: 'news.published',
|
||||
newsId: String(news._id),
|
||||
title: 'Новость опубликована',
|
||||
message: `«${news.title}» была опубликована`,
|
||||
});
|
||||
}
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/news/:id/schedule
|
||||
* Отложенная публикация: устанавливает scheduledAt.
|
||||
*
|
||||
* @param req.body.scheduledAt — ISO-дата будущего времени
|
||||
* @returns 200 { news: { id, ..., status: 'scheduled', scheduledAt } }
|
||||
*/
|
||||
newsRouter.post(
|
||||
'/:id/schedule',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
router.post('/:id/schedule', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
||||
if (!news) {
|
||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||
}
|
||||
|
||||
if (news.status === 'published') {
|
||||
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
||||
}
|
||||
|
||||
const scheduledAtRaw = bodyField(req, 'scheduledAt');
|
||||
if (typeof scheduledAtRaw !== 'string') {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть строкой (ISO-дата)');
|
||||
}
|
||||
|
||||
const scheduledAt = new Date(scheduledAtRaw);
|
||||
if (Number.isNaN(scheduledAt.getTime())) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt не является валидной датой');
|
||||
@@ -249,14 +177,25 @@ newsRouter.post(
|
||||
if (scheduledAt.getTime() <= Date.now()) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть в будущем');
|
||||
}
|
||||
|
||||
news.status = 'scheduled';
|
||||
news.scheduledAt = scheduledAt;
|
||||
news.publishedAt = null;
|
||||
await news.save();
|
||||
|
||||
if (io) {
|
||||
await createNotification(io, {
|
||||
user: userId, actor: userId, type: 'news.scheduled',
|
||||
newsId: String(news._id),
|
||||
title: 'Публикация запланирована',
|
||||
message: `«${news.title}» запланирована на ${scheduledAt.toISOString()}`,
|
||||
});
|
||||
}
|
||||
res.json({ news: serializeNews(news) });
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
return router;
|
||||
}
|
||||
/* eslint-enable max-lines-per-function */
|
||||
|
||||
/** Дефолтный экспорт (без Socket.IO). */
|
||||
const newsRouter = createNewsRouter();
|
||||
export default newsRouter;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Router, type Request, type Response } from 'express';
|
||||
|
||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
||||
import Notification from '../models/notification.model.js';
|
||||
import { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
const notificationRouter = Router();
|
||||
|
||||
// Все маршруты требуют авторизацию
|
||||
notificationRouter.use(requireAuth);
|
||||
|
||||
/**
|
||||
* Извлекает id пользователя из авторизованного запроса.
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @returns id пользователя
|
||||
*/
|
||||
function getUserId(req: Request): string {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
if (!authedReq.user) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||
}
|
||||
return authedReq.user.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирует документ уведомления для JSON.
|
||||
*
|
||||
* @param n — документ Mongoose
|
||||
* @returns объект с публичными полями
|
||||
*/
|
||||
function serializeNotification(n: InstanceType<typeof Notification>) {
|
||||
return {
|
||||
id: n._id,
|
||||
actor: n.actor,
|
||||
type: n.type,
|
||||
news: n.news,
|
||||
title: n.title,
|
||||
message: n.message,
|
||||
isRead: n.isRead,
|
||||
createdAt: n.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/notifications
|
||||
* Список уведомлений текущего пользователя (последние 50).
|
||||
*
|
||||
* @returns 200 { notifications: [...] }
|
||||
*/
|
||||
notificationRouter.get(
|
||||
'/',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const items = await Notification.find({ user: userId })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(50);
|
||||
|
||||
res.json({ notifications: items.map(serializeNotification) });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/notifications/unread-count
|
||||
* Количество непрочитанных уведомлений.
|
||||
*
|
||||
* @returns 200 { count: number }
|
||||
*/
|
||||
notificationRouter.get(
|
||||
'/unread-count',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const count = await Notification.countDocuments({ user: userId, isRead: false });
|
||||
|
||||
res.json({ count });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* PATCH /api/notifications/:id/read
|
||||
* Помечает одно уведомление как прочитанное.
|
||||
*
|
||||
* @returns 200 { notification: { ... } }
|
||||
*/
|
||||
notificationRouter.patch(
|
||||
'/:id/read',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const notification = await Notification.findOne({ _id: req.params.id, user: userId });
|
||||
if (!notification) {
|
||||
throw new ApiError(404, 'NOTIFICATION_NOT_FOUND', 'Уведомление не найдено');
|
||||
}
|
||||
|
||||
notification.isRead = true;
|
||||
await notification.save();
|
||||
|
||||
res.json({ notification: serializeNotification(notification) });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/notifications/read-all
|
||||
* Помечает все уведомления как прочитанные.
|
||||
*
|
||||
* @returns 200 { count: number } — количество помеченных
|
||||
*/
|
||||
notificationRouter.post(
|
||||
'/read-all',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const result = await Notification.updateMany(
|
||||
{ user: userId, isRead: false },
|
||||
{ $set: { isRead: true } },
|
||||
);
|
||||
|
||||
res.json({ count: result.modifiedCount });
|
||||
}),
|
||||
);
|
||||
|
||||
export default notificationRouter;
|
||||
+15
-3
@@ -4,6 +4,7 @@ import { createApp } from './app.js';
|
||||
import { connectDatabase } from './config/database.js';
|
||||
import { env } from './config/env.js';
|
||||
import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js';
|
||||
import { createSocketServer } from './socket/socketServer.js';
|
||||
|
||||
/**
|
||||
* Завершает работу процесса после закрытия сервера.
|
||||
@@ -22,13 +23,24 @@ function shutdown(signal: string, server: http.Server): void {
|
||||
/**
|
||||
* Точка входа приложения.
|
||||
*
|
||||
* Подключает MongoDB и запускает HTTP-сервер на порту из env.
|
||||
* Подключает MongoDB, создаёт HTTP-сервер, Socket.IO и Express, запускает scheduler.
|
||||
*
|
||||
* Socket.IO подключается к HTTP-серверу через engine.io (перехватывает /socket.io).
|
||||
* Express не отвечает на /socket.io (middleware в app.ts) — Socket.IO обрабатывает.
|
||||
*/
|
||||
async function main(): Promise<void> {
|
||||
await connectDatabase();
|
||||
|
||||
const app = createApp();
|
||||
const server = http.createServer(app);
|
||||
// Создаём HTTP-сервер (без handler — добавим через server.on)
|
||||
const server = http.createServer();
|
||||
|
||||
// Socket.IO подключается к HTTP-серверу (engine.io перехватывает /socket.io)
|
||||
const io = createSocketServer(server);
|
||||
|
||||
// Express-приложение (с io для news routes)
|
||||
// Express НЕ отвечает на /socket.io — middleware в app.ts
|
||||
const app = createApp({ io });
|
||||
server.on('request', app);
|
||||
|
||||
// Запускаем планировщик отложенной публикации
|
||||
startPublicationScheduler(env.schedulerIntervalMs);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import Notification from '../models/notification.model.js';
|
||||
|
||||
import type { NotificationType } from '../models/notification.model.js';
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/** Параметры для создания уведомления. */
|
||||
interface CreateNotificationParams {
|
||||
/** Пользователь-получатель. */
|
||||
user: string;
|
||||
/** Пользователь-инициатор действия. */
|
||||
actor: string;
|
||||
/** Тип события. */
|
||||
type: NotificationType;
|
||||
/** Id новости (если применимо). */
|
||||
newsId?: string;
|
||||
/** Заголовок. */
|
||||
title: string;
|
||||
/** Сообщение. */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохраняет уведомление в БД и отправляет real-time событие через Socket.IO.
|
||||
*
|
||||
* @param io — экземпляр Socket.IO server
|
||||
* @param params — данные уведомления
|
||||
* @returns сохранённое уведомление (или null, если получатель = автор — не уведомляем себя)
|
||||
*/
|
||||
export async function createNotification(
|
||||
io: SocketIOServer,
|
||||
params: CreateNotificationParams,
|
||||
): Promise<void> {
|
||||
// Не уведомляем пользователя о собственных действиях
|
||||
if (params.user === params.actor) {
|
||||
return;
|
||||
}
|
||||
|
||||
const notification = await Notification.create({
|
||||
user: params.user,
|
||||
actor: params.actor,
|
||||
type: params.type,
|
||||
news: params.newsId ?? null,
|
||||
title: params.title,
|
||||
message: params.message,
|
||||
isRead: false,
|
||||
});
|
||||
|
||||
// Отправляем real-time событие в room получателя
|
||||
io.to(`user:${params.user}`).emit('notification', {
|
||||
id: notification._id,
|
||||
type: notification.type,
|
||||
news: notification.news,
|
||||
title: notification.title,
|
||||
message: notification.message,
|
||||
isRead: false,
|
||||
createdAt: notification.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Публикует событие в room пользователя (без сохранения в БД).
|
||||
*
|
||||
* Используется для событий, которые не являются "уведомлениями"
|
||||
* в классическом смысле (например, обновление списка в реальном времени).
|
||||
*
|
||||
* @param io — экземпляр Socket.IO server
|
||||
* @param userId — получатель
|
||||
* @param event — название события
|
||||
* @param data — payload
|
||||
*/
|
||||
export function emitToUser(
|
||||
io: SocketIOServer,
|
||||
userId: string,
|
||||
event: string,
|
||||
data: unknown,
|
||||
): void {
|
||||
io.to(`user:${userId}`).emit(event, data);
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Расширение типов Socket.IO для хранения userId в socket.data.
|
||||
*/
|
||||
import type { Socket } from 'socket.io';
|
||||
|
||||
declare module 'socket.io' {
|
||||
interface Socket {
|
||||
/** Id авторизованного пользователя (устанавливается middleware). */
|
||||
userId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export type { Socket };
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Server } from 'socket.io';
|
||||
|
||||
import { env } from '../config/env.js';
|
||||
import { verifyUserToken } from '../utils/jwt.js';
|
||||
|
||||
import type { Server as HttpServer } from 'node:http';
|
||||
import type { Server as IOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Socket.IO сервер.
|
||||
*
|
||||
* @param httpServer — HTTP-сервер Express
|
||||
* @returns настроенный Socket.IO server
|
||||
*/
|
||||
export function createSocketServer(httpServer: HttpServer): IOServer {
|
||||
const io = new Server(httpServer, {
|
||||
cors: { origin: env.clientOrigins },
|
||||
});
|
||||
|
||||
// Middleware аутентификации: проверяем JWT из handshake.auth.token
|
||||
io.use((socket, next) => {
|
||||
// handshake.auth — any в типах socket.io, извлекаем token
|
||||
const token: unknown = socket.handshake.auth.token;
|
||||
|
||||
if (typeof token !== 'string' || token.length === 0) {
|
||||
next(new Error('UNAUTHORIZED: отсутствует токен'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const payload = verifyUserToken(token);
|
||||
// eslint-disable-next-line no-param-reassign -- socket.userId — стандартный паттерн Socket.IO
|
||||
socket.userId = payload.id;
|
||||
next();
|
||||
} catch {
|
||||
next(new Error('UNAUTHORIZED: недействительный токен'));
|
||||
}
|
||||
});
|
||||
|
||||
// При подключении — добавляем socket в room пользователя
|
||||
io.on('connection', (socket) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- socket.join fire-and-forget
|
||||
void socket.join(`user:${socket.userId}`);
|
||||
});
|
||||
|
||||
return io;
|
||||
}
|
||||
Reference in New Issue
Block a user