Phase 3: News CRUD — model, endpoints, ownership, интеграционные тесты
This commit is contained in:
@@ -7,6 +7,7 @@ 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';
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Express-приложение.
|
||||
@@ -38,6 +39,7 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
|
||||
// API-маршруты
|
||||
app.use('/api', healthRouter);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/news', newsRouter);
|
||||
|
||||
// Дополнительные middleware (тестовые маршруты, заглушки)
|
||||
if (extraMiddleware) {
|
||||
|
||||
@@ -40,7 +40,7 @@ export function requireAuth(req: Request, _res: Response, next: NextFunction): v
|
||||
|
||||
try {
|
||||
const payload = verifyUserToken(token);
|
||||
// eslint-disable-next-line no-param-reassign -- установка req.user для последующих обработчиков
|
||||
// eslint-disable-next-line no-param-reassign, @typescript-eslint/consistent-type-assertions -- установка req.user
|
||||
(req as AuthenticatedRequest).user = { id: payload.id };
|
||||
next();
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Schema, model, type HydratedDocument, type Types } from 'mongoose';
|
||||
|
||||
export type NewsStatus = 'draft' | 'scheduled' | 'published';
|
||||
|
||||
export interface INews {
|
||||
title: string;
|
||||
content: string;
|
||||
status: NewsStatus;
|
||||
author: Types.ObjectId;
|
||||
scheduledAt: Date | null;
|
||||
publishedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export type NewsDocument = HydratedDocument<INews>;
|
||||
|
||||
const newsSchema = new Schema<INews>(
|
||||
{
|
||||
title: {
|
||||
type: String,
|
||||
required: [true, 'Название новости обязательно'],
|
||||
trim: true,
|
||||
maxlength: [200, 'Название не должно превышать 200 символов'],
|
||||
},
|
||||
content: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: ['draft', 'scheduled', 'published'],
|
||||
default: 'draft',
|
||||
},
|
||||
author: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
required: [true, 'Автор новости обязателен'],
|
||||
},
|
||||
scheduledAt: {
|
||||
type: Date,
|
||||
default: null,
|
||||
},
|
||||
publishedAt: {
|
||||
type: Date,
|
||||
default: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
toJSON: { virtuals: true },
|
||||
toObject: { virtuals: true },
|
||||
},
|
||||
);
|
||||
|
||||
// Индекс для scheduler: поиск scheduled новостей с прошлым scheduledAt
|
||||
newsSchema.index({ status: 1, scheduledAt: 1 });
|
||||
|
||||
const News = model<INews>('News', newsSchema);
|
||||
|
||||
export default News;
|
||||
@@ -119,7 +119,8 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
||||
* @returns 200 { id, email }
|
||||
*/
|
||||
authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Response) => {
|
||||
// req.headers['x-user-id'] установлен requireAuth middleware
|
||||
// req.user установлен requireAuth middleware
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
if (authedReq.user === undefined) {
|
||||
res.status(401).json({ error: { code: 'UNAUTHORIZED', message: 'Требуется авторизация' } });
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
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 { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
const newsRouter = Router();
|
||||
|
||||
// Сообщение об авторизации
|
||||
const AUTH_MSG = 'Требуется авторизация';
|
||||
// Сообщение о не найденной новости
|
||||
const NOT_FOUND_MSG = 'Новость не найдена';
|
||||
|
||||
// Все маршруты требуют авторизацию
|
||||
newsRouter.use(requireAuth);
|
||||
|
||||
/**
|
||||
* Возвращает id авторизованного пользователя или бросает 401.
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @returns id пользователя (string)
|
||||
*/
|
||||
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', AUTH_MSG);
|
||||
}
|
||||
return authedReq.user.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Безопасно извлекает поле из req.body (any → unknown).
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @param key — имя поля
|
||||
* @returns значение поля (unknown)
|
||||
*/
|
||||
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
|
||||
const raw = (req.body ?? {}) as Record<string, unknown>;
|
||||
return raw[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирует Mongoose-документ новости для JSON-ответа.
|
||||
*
|
||||
* @param n — документ Mongoose
|
||||
* @returns объект с публичными полями
|
||||
*/
|
||||
function serializeNews(n: InstanceType<typeof News>) {
|
||||
return {
|
||||
id: n._id,
|
||||
title: n.title,
|
||||
content: n.content,
|
||||
status: n.status,
|
||||
scheduledAt: n.scheduledAt,
|
||||
publishedAt: n.publishedAt,
|
||||
createdAt: n.createdAt,
|
||||
updatedAt: n.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/news
|
||||
* Список новостей пользователя (все статусы).
|
||||
*
|
||||
* @returns 200 { news: [...] }
|
||||
*/
|
||||
newsRouter.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) => {
|
||||
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) => {
|
||||
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) => {
|
||||
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', 'Название обязательно');
|
||||
}
|
||||
if (title.trim().length > 200) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов');
|
||||
}
|
||||
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) => {
|
||||
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);
|
||||
}
|
||||
|
||||
await news.deleteOne();
|
||||
res.status(204).send();
|
||||
}),
|
||||
);
|
||||
|
||||
export default newsRouter;
|
||||
Reference in New Issue
Block a user