import { Injectable, NotFoundException } from '@nestjs/common'; import { Prisma } from '@prisma/client'; import { PrismaService } from '../prisma/prisma.service'; export class CategoryQuery { page?: number | string; limit?: number | string; search?: string; } @Injectable() export class CategoriesService { constructor(private prisma: PrismaService) {} async getCategories(query: CategoryQuery = {}) { const page = Number(query.page) || 1; const limit = Number(query.limit) || 10; const skip = (page - 1) * limit; const where: Prisma.CategoryWhereInput = query.search ? { name: { contains: query.search, mode: 'insensitive' } } : {}; const [data, total] = await Promise.all([ this.prisma.category.findMany({ where, skip, take: limit, orderBy: { createdAt: 'desc' }, }), this.prisma.category.count({ where }), ]); return { data, meta: { total, page, limit, lastPage: Math.ceil(total / limit), }, }; } async getAllCategoriesRaw() { return this.prisma.category.findMany({ orderBy: { name: 'asc' } }); } async createCategory(data: Prisma.CategoryCreateInput) { const nameStr = data.name || ''; const slugStr = data.slug || nameStr.replace(/\s+/g, '-').toLowerCase(); return this.prisma.category.create({ data: { ...data, slug: slugStr, }, }); } async updateCategory(id: string, data: Prisma.CategoryUpdateInput) { const category = await this.prisma.category.findUnique({ where: { id } }); if (!category) throw new NotFoundException('Category not found'); return this.prisma.category.update({ where: { id }, data }); } async deleteCategory(id: string) { const category = await this.prisma.category.findUnique({ where: { id } }); if (!category) throw new NotFoundException('Category not found'); return this.prisma.category.delete({ where: { id } }); } }