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
@@ -0,0 +1,57 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateCategoryDto } from '../dto/create-category.dto';
import { UpdateCategoryDto } from '../dto/update-category.dto';
import { CategoryRepository } from '../repositories/category.repository';
import { EntityManager } from '@mikro-orm/postgresql';
import { RequiredEntityData, FilterQuery } from '@mikro-orm/core';
import { Category } from '../entities/category.entity';
import { CategoryMessage } from 'src/common/enums/message.enum';
@Injectable()
export class CategoryService {
constructor(
private readonly categoryRepository: CategoryRepository,
private readonly em: EntityManager,
) {}
async create(dto: CreateCategoryDto): Promise<Category> {
const data = {
title: dto.title,
isActive: dto.isActive ?? true,
restId: dto.restId,
avatarUrl: dto.avatarUrl,
} as RequiredEntityData<Category>;
const category = this.categoryRepository.create(data);
await this.em.persistAndFlush(category);
return category;
}
async findAll(opts?: { restId?: string; isActive?: boolean }): Promise<Category[]> {
const where: FilterQuery<Category> = {};
if (opts?.restId) where.restId = opts.restId;
if (opts && typeof opts.isActive === 'boolean') where.isActive = opts.isActive;
return this.categoryRepository.find(where, { populate: ['foods'] });
}
async findOne(id: string): Promise<Category> {
const cat = await this.categoryRepository.findOne({ id }, { populate: ['foods'] });
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
return cat;
}
async update(id: string, dto: UpdateCategoryDto): Promise<Category> {
const cat = await this.categoryRepository.findOne({ id });
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
this.em.assign(cat, dto as Partial<Category>);
await this.em.persistAndFlush(cat);
return cat;
}
async remove(id: string): Promise<void> {
const cat = await this.categoryRepository.findOne({ id });
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
cat.deletedAt = new Date();
await this.em.persistAndFlush(cat);
}
}