import { Injectable } from '@nestjs/common'; import { EntityManager, EntityRepository } from '@mikro-orm/postgresql'; import { FilterQuery } from '@mikro-orm/core'; import { Product } from '../entities/product.entity'; import { PaginatedResult } from 'src/common/interfaces/pagination.interface'; type FindproductsOpts = { page?: number; limit?: number; search?: string; orderBy?: string; order?: 'asc' | 'desc'; categoryId?: string; isActive?: boolean; }; @Injectable() export class ProductRepository extends EntityRepository { constructor(readonly em: EntityManager) { super(em, Product); } async findAllPaginated(opts: FindproductsOpts = {}): Promise> { const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', categoryId, isActive } = opts; const offset = (page - 1) * limit; const where: FilterQuery = {}; if (typeof isActive === 'boolean') { where.isActive = isActive; } if (search) { const pattern = `%${search}%`; where.$or = [{ title: { $ilike: pattern } },]; } if (categoryId) { // filter by related category (product has a single `category` relation) Object.assign(where, { category: { id: categoryId } } as unknown as FilterQuery); } const [data, total] = await this.findAndCount(where, { limit, offset, orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' }, populate: [], }); const totalPages = Math.ceil(total / limit); return { data, meta: { total, page, limit, totalPages, }, }; } }