Phase 3: News CRUD — model, endpoints, ownership, интеграционные тесты
This commit is contained in:
@@ -256,9 +256,14 @@ export default defineConfig(
|
||||
'max-statements': 'off',
|
||||
'sonarjs/cognitive-complexity': 'off',
|
||||
'sonarjs/no-duplicate-string': 'off',
|
||||
'sonarjs/no-hardcoded-passwords': 'off',
|
||||
'import-x/no-extraneous-dependencies': ['error', { devDependencies: true }],
|
||||
'@typescript-eslint/no-floating-promises': 'off',
|
||||
'@typescript-eslint/require-await': 'off',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||
'@typescript-eslint/restrict-template-expressions': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
@@ -182,7 +182,7 @@ describe('Auth', () => {
|
||||
const regRes: Response = await request(app).post('/api/auth/register').send(creds);
|
||||
const token = tokenOf(regRes.body);
|
||||
expect(token).toBeDefined();
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- token проверен
|
||||
|
||||
const authHeader = `Bearer ${token}`;
|
||||
|
||||
const res = await request(app)
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import request from 'supertest';
|
||||
import { describe, expect, it, beforeAll } from 'vitest';
|
||||
|
||||
import { createApp } from '../src/app.js';
|
||||
import { User, hashPassword } from '../src/models/user.model.js';
|
||||
import { signUserToken } from '../src/utils/jwt.js';
|
||||
|
||||
const app = createApp();
|
||||
const TEST_EMAIL = 'news-test@example.com';
|
||||
const TEST_PASSWORD = 'Test-Pass-123';
|
||||
|
||||
|
||||
let authToken = '';
|
||||
|
||||
beforeAll(async () => {
|
||||
// Создаём пользователя через model
|
||||
const user = await User.create({ email: TEST_EMAIL, passwordHash: await hashPassword(TEST_PASSWORD) });
|
||||
|
||||
|
||||
authToken = signUserToken(user.id);
|
||||
});
|
||||
|
||||
function authed(req: request.Test): request.Test {
|
||||
return req.set('Authorization', `Bearer ${authToken}`);
|
||||
}
|
||||
|
||||
describe('News CRUD', () => {
|
||||
describe('GET /api/news', () => {
|
||||
it('без токена возвращает 401', async () => {
|
||||
const res = await request(app).get('/api/news');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('с токеном возвращает пустой список', async () => {
|
||||
const res = await authed(request(app).get('/api/news'));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.news).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/news', () => {
|
||||
it('создаёт новость (draft)', async () => {
|
||||
const res = await authed(
|
||||
request(app).post('/api/news').send({ title: 'Тестовая новость', content: '# Привет' }),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.news.title).toBe('Тестовая новость');
|
||||
expect(res.body.news.content).toBe('# Привет');
|
||||
expect(res.body.news.status).toBe('draft');
|
||||
});
|
||||
|
||||
it('без названия возвращает 400', async () => {
|
||||
const res = await authed(request(app).post('/api/news').send({ content: 'текст' }));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('название > 200 символов возвращает 400', async () => {
|
||||
const longTitle = 'а'.repeat(201);
|
||||
const res = await authed(request(app).post('/api/news').send({ title: longTitle }));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/news/:id', () => {
|
||||
it('возвращает новость по id', async () => {
|
||||
const createRes = await authed(request(app).post('/api/news').send({ title: 'Для чтения' }));
|
||||
const newsId = createRes.body.news.id;
|
||||
|
||||
const res = await authed(request(app).get(`/api/news/${newsId}`));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.news.id).toBe(newsId);
|
||||
expect(res.body.news.title).toBe('Для чтения');
|
||||
});
|
||||
|
||||
it('несуществующий id возвращает 404', async () => {
|
||||
const res = await authed(request(app).get('/api/news/000000000000000000000000'));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('чужая новость возвращает 404', async () => {
|
||||
// Создаём новость от первого пользователя
|
||||
const createRes = await authed(request(app).post('/api/news').send({ title: 'Своя' }));
|
||||
const ownNewsId = createRes.body.news.id;
|
||||
|
||||
// Создаём второго пользователя
|
||||
const user2 = await User.create({ email: 'other-news@example.com', passwordHash: await hashPassword('Other-Pass-123') });
|
||||
const token2 = signUserToken(user2.id);
|
||||
|
||||
const res = await request(app)
|
||||
.get(`/api/news/${ownNewsId}`)
|
||||
.set('Authorization', `Bearer ${token2}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/news/:id', () => {
|
||||
it('обновляет title', async () => {
|
||||
const createRes = await authed(request(app).post('/api/news').send({ title: 'Оригинал' }));
|
||||
const newsId = createRes.body.news.id;
|
||||
|
||||
const res = await authed(request(app).patch(`/api/news/${newsId}`).send({ title: 'Обновлено' }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.news.title).toBe('Обновлено');
|
||||
});
|
||||
|
||||
it('обновляет content', async () => {
|
||||
const createRes = await authed(request(app).post('/api/news').send({ title: 'Оригинал' }));
|
||||
const newsId = createRes.body.news.id;
|
||||
|
||||
const res = await authed(request(app).patch(`/api/news/${newsId}`).send({ content: 'Новый контент' }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.news.content).toBe('Новый контент');
|
||||
});
|
||||
|
||||
it('обновляет title и content одновременно', async () => {
|
||||
const createRes = await authed(request(app).post('/api/news').send({ title: 'Оригинал' }));
|
||||
const newsId = createRes.body.news.id;
|
||||
|
||||
const res = await authed(
|
||||
request(app).patch(`/api/news/${newsId}`).send({ title: 'Оба', content: 'Контент' }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.news.title).toBe('Оба');
|
||||
expect(res.body.news.content).toBe('Контент');
|
||||
});
|
||||
|
||||
it('несуществующий id возвращает 404', async () => {
|
||||
const res = await authed(
|
||||
request(app).patch('/api/news/000000000000000000000000').send({ title: 'x' }),
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/news/:id', () => {
|
||||
it('удаляет новость', async () => {
|
||||
const createRes = await authed(request(app).post('/api/news').send({ title: 'К удалению' }));
|
||||
const id = createRes.body.news.id;
|
||||
|
||||
const delRes = await authed(request(app).delete(`/api/news/${id}`));
|
||||
expect(delRes.status).toBe(204);
|
||||
|
||||
const getRes = await authed(request(app).get(`/api/news/${id}`));
|
||||
expect(getRes.status).toBe(404);
|
||||
});
|
||||
|
||||
it('несуществующий id возвращает 404', async () => {
|
||||
const res = await authed(request(app).delete('/api/news/000000000000000000000000'));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('чужая новость — 404', async () => {
|
||||
const createRes = await authed(request(app).post('/api/news').send({ title: 'Своя' }));
|
||||
const id = createRes.body.news.id;
|
||||
|
||||
const user2 = await User.create({ email: 'del-other@example.com', passwordHash: await hashPassword('Other-Pass-123') });
|
||||
const token2 = signUserToken(user2.id);
|
||||
|
||||
const res = await request(app)
|
||||
.delete(`/api/news/${id}`)
|
||||
.set('Authorization', `Bearer ${token2}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { afterAll, beforeEach } from 'vitest';
|
||||
|
||||
import News from '../src/models/news.model.js';
|
||||
import { User } from '../src/models/user.model.js';
|
||||
|
||||
// Подключаем Mongoose (MONGODB_URI установлен в global-setup)
|
||||
@@ -18,6 +19,7 @@ await mongoose.connect(mongoUri);
|
||||
|
||||
beforeEach(async () => {
|
||||
await User.deleteMany({});
|
||||
await News.deleteMany({});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
|
||||
Reference in New Issue
Block a user