Дополнительный комит.
This commit is contained in:
parent
d9ab710be4
commit
de7c309121
@ -147,7 +147,7 @@ export async function createArticle(req: AuthRequest, res: Response) : Promise<v
|
||||
|
||||
export async function updateArticle(req: AuthRequest, res: Response) : Promise<void> {
|
||||
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<v
|
||||
};
|
||||
}
|
||||
|
||||
const updatedArticle = await prisma.article.update({
|
||||
where: { id: req.params.id },
|
||||
data: updateData,
|
||||
include: {
|
||||
authors: {
|
||||
include: {
|
||||
author: {
|
||||
select: {
|
||||
id: true,
|
||||
displayName: true,
|
||||
email: true,
|
||||
// Используется транзакция для атомарного обновления статьи и галереи
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
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: 'Серверная ошибка' });
|
||||
|
||||
@ -9,8 +9,8 @@ import { AuthorRole } from "@prisma/client";
|
||||
export async function getAuthors(req: AuthRequest, res: Response): Promise<void> {
|
||||
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' });
|
||||
}
|
||||
|
||||
@ -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<Author[]> => {
|
||||
getAuthors: async (page: number, role?: string): Promise<AuthorsResponse> => {
|
||||
|
||||
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('Ошибка получения авторов');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user