import { BadRequestException, Injectable, NotFoundException, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { UserRole } from '../users/enums/user-role.enum'; import { UsersService } from '../users/users.service'; import { CreateSalonDto } from './dto/create-salon.dto'; import { UpdateSalonDto } from './dto/update-salon.dto'; import { Salon } from './entities/salon.entity'; @Injectable() export class SalonsService { constructor( @InjectRepository(Salon) private readonly salonsRepository: Repository, private readonly usersService: UsersService, ) {} async create(createSalonDto: CreateSalonDto): Promise { await this.ensureOwnerIsSalonOwner(createSalonDto.ownerId); const salon = this.salonsRepository.create(createSalonDto); return this.salonsRepository.save(salon); } findAll(): Promise { return this.salonsRepository.find({ relations: { owner: true } }); } async findOne(id: string): Promise { const salon = await this.salonsRepository.findOne({ where: { id }, relations: { owner: true }, }); if (!salon) { throw new NotFoundException(`Salon #${id} not found`); } return salon; } async update(id: string, updateSalonDto: UpdateSalonDto): Promise { const salon = await this.findOne(id); Object.assign(salon, updateSalonDto); return this.salonsRepository.save(salon); } async remove(id: string): Promise { const salon = await this.findOne(id); await this.salonsRepository.remove(salon); } private async ensureOwnerIsSalonOwner(ownerId: string): Promise { const owner = await this.usersService.findOne(ownerId); if (owner.role !== UserRole.SALON) { throw new BadRequestException('Owner must have salon-owner role'); } } }