Дополнительный комит.
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> {
|
export async function updateArticle(req: AuthRequest, res: Response) : Promise<void> {
|
||||||
try {
|
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) {
|
if (!req.user) {
|
||||||
res.status(401).json({ error: 'Пользователь не вошел в систему' });
|
res.status(401).json({ error: 'Пользователь не вошел в систему' });
|
||||||
@ -191,8 +191,10 @@ export async function updateArticle(req: AuthRequest, res: Response) : Promise<v
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Используется транзакция для атомарного обновления статьи и галереи
|
||||||
|
const result = await prisma.$transaction(async (tx) => {
|
||||||
const updatedArticle = await prisma.article.update({
|
const updatedArticle = await prisma.article.update({
|
||||||
where: { id: req.params.id },
|
where: {id: req.params.id},
|
||||||
data: updateData,
|
data: updateData,
|
||||||
include: {
|
include: {
|
||||||
authors: {
|
authors: {
|
||||||
@ -209,7 +211,33 @@ export async function updateArticle(req: AuthRequest, res: Response) : Promise<v
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Обработка обновления галереи
|
||||||
|
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);
|
res.json(updatedArticle);
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Ошибка редактирования статьи:', error);
|
logger.error('Ошибка редактирования статьи:', error);
|
||||||
res.status(500).json({ 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> {
|
export async function getAuthors(req: AuthRequest, res: Response): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const { role, page } = req.query;
|
const { role, page } = req.query;
|
||||||
const authors = await authorService.getAuthors(Number(page), role as string);
|
const response = await authorService.getAuthors(Number(page), role as string);
|
||||||
res.json(authors);
|
res.json(response);
|
||||||
} catch {
|
} catch {
|
||||||
res.status(500).json({ error: 'Server error' });
|
res.status(500).json({ error: 'Server error' });
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,8 +4,15 @@ import { Author } from '../types/auth';
|
|||||||
|
|
||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
export interface AuthorsResponse {
|
||||||
|
authors: Author[];
|
||||||
|
totalPages: number,
|
||||||
|
currentPage: number,
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
export const authorService = {
|
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)) {
|
if (role && !Object.values(AuthorRole).includes(role as AuthorRole)) {
|
||||||
throw new Error(`Недопустимая роль: ${role}`);
|
throw new Error(`Недопустимая роль: ${role}`);
|
||||||
@ -25,6 +32,14 @@ export const authorService = {
|
|||||||
const take = page ? pageSize : undefined;
|
const take = page ? pageSize : undefined;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 0. Считаем общее количество авторов (без skip/take)
|
||||||
|
const total = await prisma.author.count({
|
||||||
|
where: {
|
||||||
|
order: { not: 0 },
|
||||||
|
...sortRoles,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
// 1. Получаем авторов
|
// 1. Получаем авторов
|
||||||
const authors = await prisma.author.findMany({
|
const authors = await prisma.author.findMany({
|
||||||
select: {
|
select: {
|
||||||
@ -44,7 +59,7 @@ export const authorService = {
|
|||||||
select: {
|
select: {
|
||||||
articles: {
|
articles: {
|
||||||
where: {
|
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 rawLikes: { authorId: string; totalLikes: number | null }[] = await prisma.$queryRawUnsafe(sql, role);
|
||||||
const likesMap = new Map(rawLikes.map(item => [item.authorId, item.totalLikes ?? 0]));
|
const likesMap = new Map(rawLikes.map(item => [item.authorId, item.totalLikes ?? 0]));
|
||||||
|
|
||||||
return authors.map(author => ({
|
const fullArticles = authors.map(author => ({
|
||||||
id: author.id,
|
id: author.id,
|
||||||
displayName: author.displayName,
|
displayName: author.displayName,
|
||||||
avatarUrl: author.avatarUrl,
|
avatarUrl: author.avatarUrl,
|
||||||
@ -93,8 +108,15 @@ export const authorService = {
|
|||||||
userDisplayName: author.user?.displayName || null,
|
userDisplayName: author.user?.displayName || null,
|
||||||
isActive: author.isActive,
|
isActive: author.isActive,
|
||||||
roles: author.roles,
|
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) {
|
} catch (error) {
|
||||||
console.error('Ошибка получения авторов:', error);
|
console.error('Ошибка получения авторов:', error);
|
||||||
throw new Error('Ошибка получения авторов');
|
throw new Error('Ошибка получения авторов');
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user