/
MariaTsys
/
courseworkPP
Обзор
Документация
Войти
/
MariaTsys
/
courseworkPP
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/server/api/routers/admin.ts
125 строк
4 KB
Maria
first_commit
09 май 2025, 12:17
09 май 2025, 12:17
af55308
Код
Авторство
О чём код?
// app/server/api/routers/adminRouter.ts import { z } from "zod"; import { isAdmin } from "~/app/api/auth/check"; import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc"; import { db } from "~/server/db"; import { minioClient } from "../minio/client"; export const adminRouter = createTRPCRouter({ getAllUsers: protectedProcedure.query(async ({ ctx }) => { if (!(await isAdmin())) throw new Error("Unauthorized"); return await ctx.db.user.findMany({ select: { id: true, name: true, email: true, role: true, }, }); }), deleteUser: protectedProcedure .input(z.object({ userId: z.string() })) .mutation(async ({ ctx, input }) => { if (!(await isAdmin())) throw new Error("Unauthorized"); if (ctx.session.user.id === input.userId) { return { error: "Нельзя удалить самого себя" }; } await ctx.db.user.delete({ where: { id: input.userId }, }); return { success: true }; }), // ⬇ Добавляем новый роут для загрузки книги uploadBook: protectedProcedure .input( z.object({ title: z.string(), author: z.string(), genre: z.string().optional(), coverUrl: z.string().url().optional(), content: z.string(), }) ) .mutation(async ({ input }) => { const { title, author, genre, coverUrl, content } = input; // 1. Сохраняем книгу в БД const newBook = await db.book.create({ data: { title, author, genre, coverUrl, }, }); // 2. Загружаем файл в MinIO const fileName = `${newBook.id}.txt`; const buffer = Buffer.from(content, "utf-8"); await minioClient.putObject(process.env.MINIO_BUCKET_NAME!, fileName, buffer); return { success: true, bookId: newBook.id }; }), deleteBook: protectedProcedure .input(z.object({ bookId: z.string() })) .mutation(async ({ input }) => { if (!(await isAdmin())) throw new Error("Unauthorized"); // Удаляем из MinIO const fileName = `${input.bookId}.txt`; try { await minioClient.removeObject(process.env.MINIO_BUCKET_NAME!, fileName); } catch (error) { console.warn("Не удалось удалить файл из MinIO:", error); // Продолжаем, даже если файла нет — чтобы не блокировать удаление из БД } // Удаляем из базы данных await db.book.delete({ where: { id: input.bookId }, }); return { success: true }; }), getAllBooks: protectedProcedure .input( z.object({ page: z.number().min(1).default(1), limit: z.number().min(1).max(100).default(10), }) ) .query(async ({ input, ctx }) => { const { page, limit } = input; const skip = (page - 1) * limit; const [books, total] = await Promise.all([ ctx.db.book.findMany({ skip, take: limit, select: { id: true, title: true, author: true, }, orderBy: { createdAt: "desc", }, }), ctx.db.book.count(), ]); return { books, total, }; }), });