From de7c3091215db464ed62ae1731efea2af4855de2 Mon Sep 17 00:00:00 2001 From: anibilag Date: Sun, 5 Oct 2025 00:46:09 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD=D0=B8?= =?UTF-8?q?=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=B8=D1=82.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/routes/articles/controllers/crud.ts | 58 +++++++++++++++++------ src/routes/authors/controllers/authors.ts | 4 +- src/services/authorService.ts | 30 ++++++++++-- 3 files changed, 71 insertions(+), 21 deletions(-) diff --git a/src/routes/articles/controllers/crud.ts b/src/routes/articles/controllers/crud.ts index 0181b11..56bcac8 100644 --- a/src/routes/articles/controllers/crud.ts +++ b/src/routes/articles/controllers/crud.ts @@ -147,7 +147,7 @@ export async function createArticle(req: AuthRequest, res: Response) : Promise { try { - const { title, excerpt, content, categoryId, cityId, coverImage, readTime, authors } = req.body; + const { title, excerpt, content, categoryId, cityId, coverImage, readTime, authors, gallery = [] } = req.body; if (!req.user) { res.status(401).json({ error: 'Пользователь не вошел в систему' }); @@ -191,25 +191,53 @@ export async function updateArticle(req: AuthRequest, res: Response) : Promise { + const updatedArticle = await prisma.article.update({ + where: {id: req.params.id}, + data: updateData, + include: { + authors: { + include: { + author: { + select: { + id: true, + displayName: true, + email: true, + }, }, }, }, }, - }, - }); + }); - res.json(updatedArticle); + // Обработка обновления галереи + if (gallery && Array.isArray(gallery)) { + // Вначале удалить все существующие изображения из галереи статьи + await prisma.galleryImage.deleteMany({ + where: {articleId: req.params.id} + }); + + // Создать новые изображения галереи + if (gallery.length > 0) { + await prisma.galleryImage.createMany({ + data: gallery.map((image: any, index: number) => ({ + articleId: req.params.id, + url: image.url, + caption: image.caption || '', + alt: image.alt || '', + width: image.width || 0, + height: image.height || 0, + size: image.size || 0, + format: image.format || 'webp', + order: index + })) + }); + } + } + + res.json(updatedArticle); + }); } catch (error) { logger.error('Ошибка редактирования статьи:', error); res.status(500).json({ error: 'Серверная ошибка' }); diff --git a/src/routes/authors/controllers/authors.ts b/src/routes/authors/controllers/authors.ts index ae7f375..61d7bd4 100644 --- a/src/routes/authors/controllers/authors.ts +++ b/src/routes/authors/controllers/authors.ts @@ -9,8 +9,8 @@ import { AuthorRole } from "@prisma/client"; export async function getAuthors(req: AuthRequest, res: Response): Promise { try { const { role, page } = req.query; - const authors = await authorService.getAuthors(Number(page), role as string); - res.json(authors); + const response = await authorService.getAuthors(Number(page), role as string); + res.json(response); } catch { res.status(500).json({ error: 'Server error' }); } diff --git a/src/services/authorService.ts b/src/services/authorService.ts index 1c20f72..fdb5a67 100644 --- a/src/services/authorService.ts +++ b/src/services/authorService.ts @@ -4,8 +4,15 @@ import { Author } from '../types/auth'; const prisma = new PrismaClient(); +export interface AuthorsResponse { + authors: Author[]; + totalPages: number, + currentPage: number, + total: number; +} + export const authorService = { - getAuthors: async (page: number, role?: string): Promise => { + getAuthors: async (page: number, role?: string): Promise => { if (role && !Object.values(AuthorRole).includes(role as AuthorRole)) { throw new Error(`Недопустимая роль: ${role}`); @@ -25,6 +32,14 @@ export const authorService = { const take = page ? pageSize : undefined; try { + // 0. Считаем общее количество авторов (без skip/take) + const total = await prisma.author.count({ + where: { + order: { not: 0 }, + ...sortRoles, + }, + }); + // 1. Получаем авторов const authors = await prisma.author.findMany({ select: { @@ -44,7 +59,7 @@ export const authorService = { select: { articles: { where: { - role: role as AuthorRole, // 👈 учитываются только WRITER-авторы + role: role as AuthorRole, }, }, }, @@ -78,7 +93,7 @@ export const authorService = { const rawLikes: { authorId: string; totalLikes: number | null }[] = await prisma.$queryRawUnsafe(sql, role); const likesMap = new Map(rawLikes.map(item => [item.authorId, item.totalLikes ?? 0])); - return authors.map(author => ({ + const fullArticles = authors.map(author => ({ id: author.id, displayName: author.displayName, avatarUrl: author.avatarUrl, @@ -93,8 +108,15 @@ export const authorService = { userDisplayName: author.user?.displayName || null, isActive: author.isActive, roles: author.roles, - totalLikes: Number(likesMap.get(author.id) ?? 0), + totalLikes: Number(likesMap.get(author.id) ?? 0) })); + + return { + authors: fullArticles, + totalPages: Math.ceil(total / pageSize), + currentPage: page, + total: total + }; } catch (error) { console.error('Ошибка получения авторов:', error); throw new Error('Ошибка получения авторов');