65 lines
1.6 KiB
TypeScript
65 lines
1.6 KiB
TypeScript
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<Product> {
|
|
constructor(readonly em: EntityManager) {
|
|
super(em, Product);
|
|
}
|
|
|
|
async findAllPaginated(opts: FindproductsOpts = {}): Promise<PaginatedResult<Product>> {
|
|
const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', categoryId, isActive } = opts;
|
|
|
|
const offset = (page - 1) * limit;
|
|
|
|
const where: FilterQuery<Product> = {};
|
|
|
|
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<Product>);
|
|
}
|
|
|
|
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,
|
|
},
|
|
};
|
|
|
|
}
|
|
}
|