This commit is contained in:
2025-11-15 08:41:35 +03:30
parent 15c0c508b9
commit 0f1407c748
23 changed files with 714 additions and 177 deletions
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common';
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
import { Category } from '../entities/category';
import { Category } from '../entities/category.entity';
@Injectable()
export class CategoryRepository extends EntityRepository<Category> {
@@ -1,10 +1,66 @@
import { Injectable } from '@nestjs/common';
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
import { FilterQuery } from '@mikro-orm/core';
import { Foods } from '../entities/food.entity';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
type FindFoodsOpts = {
page?: number;
limit?: number;
search?: string;
orderBy?: string;
order?: 'asc' | 'desc';
categoryId?: string;
isActive?: boolean;
};
@Injectable()
export class FoodRepository extends EntityRepository<Foods> {
constructor(readonly em: EntityManager) {
super(em, Foods);
}
/**
* Find foods with pagination and optional filters.
* Supports: search (title/content), categoryId, isActive, ordering.
*/
async findAllPaginated(opts: FindFoodsOpts = {}): Promise<PaginatedResult<Foods>> {
const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', categoryId, isActive } = opts;
const offset = (page - 1) * limit;
const where: FilterQuery<Foods> = {};
if (typeof isActive === 'boolean') {
where.isActive = isActive;
}
if (search) {
const pattern = `%${search}%`;
where.$or = [{ title: { $ilike: pattern } }, { content: { $ilike: pattern } }];
}
if (categoryId) {
// filter by related categories (typed via FilterQuery)
Object.assign(where, { categories: { id: categoryId } } as unknown as FilterQuery<Foods>);
}
const [data, total] = await this.findAndCount(where, {
limit,
offset,
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
populate: ['categories'],
});
const totalPages = Math.ceil(total / limit);
return {
data,
meta: {
total,
page,
limit,
totalPages,
},
};
}
}