65 lines
2.2 KiB
TypeScript
65 lines
2.2 KiB
TypeScript
import { Request, Response } from 'express';
|
||
import { prisma } from '../../../lib/prisma';
|
||
import { Prisma } from '@prisma/client';
|
||
|
||
|
||
export async function listArticles(req: Request, res: Response) {
|
||
try {
|
||
let page = Number(req.query.page);
|
||
if (!Number.isInteger(page) || page < 1) page = 1; // Гарантируем, что `page` - корректное число
|
||
|
||
const perPage = 6;
|
||
|
||
const isActiveParam = req.query.isDraft;
|
||
|
||
// Преобразование и проверка categoryId и cityId
|
||
const catId = Number(req.query.categoryId);
|
||
const citId = Number(req.query.cityId);
|
||
|
||
const authorId = req.query.userId ? String(req.query.userId) : undefined; // Приводим к строке - это UUID
|
||
const isAdmin = Boolean(req.query.isAdmin);
|
||
|
||
const where: Prisma.ArticleWhereInput = {
|
||
...(Number.isInteger(catId) && catId > 0 ? { categoryId: catId } : {}),
|
||
...(Number.isInteger(citId) && citId > 0 ? { cityId: citId } : {}),
|
||
...(isActiveParam === "true" ? { isActive: false } : isActiveParam === "false" ? {} : { isActive: true }),
|
||
...(authorId && !isAdmin ? { authorId } : {}), // Добавляем authorId в фильтр
|
||
};
|
||
|
||
// Рассчитываем пропуск записей
|
||
const skip = (page - 1) * perPage;
|
||
|
||
// Выполняем два параллельных запроса: получение статей и подсчёт общего количества
|
||
const [articles, total] = await Promise.all([
|
||
prisma.article.findMany({
|
||
where,
|
||
include: {
|
||
author: {
|
||
select: {
|
||
id: true,
|
||
displayName: true,
|
||
avatarUrl: true,
|
||
email: true
|
||
},
|
||
},
|
||
},
|
||
skip,
|
||
take: perPage,
|
||
orderBy: { publishedAt: 'desc' },
|
||
}),
|
||
prisma.article.count({ where }),
|
||
]);
|
||
|
||
// Формируем ответ
|
||
res.json({
|
||
articles,
|
||
totalPages: Math.ceil(total / perPage),
|
||
currentPage: page,
|
||
});
|
||
} catch (error) {
|
||
// Логируем ошибку и отправляем ответ с кодом 500
|
||
console.error('Error during articles list:', error);
|
||
res.status(500).json({ error: 'Server error' });
|
||
}
|
||
}
|