mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 21:20:57 +00:00
62 lines
1.8 KiB
TypeScript
62 lines
1.8 KiB
TypeScript
import {
|
|
ConflictException,
|
|
Injectable,
|
|
NotFoundException,
|
|
} from "@nestjs/common";
|
|
|
|
import { CustomersRepository } from "./customers.repository";
|
|
import { CreateCustomerDto } from "./dto/create-customer.dto";
|
|
import { UpdateCustomerDto } from "./dto/update-customer.dto";
|
|
import { Customer } from "./entities/customer.entity";
|
|
|
|
@Injectable()
|
|
export class CustomersService {
|
|
constructor(private readonly customersRepository: CustomersRepository) {}
|
|
|
|
async create(dto: CreateCustomerDto): Promise<Customer> {
|
|
const existing = await this.customersRepository.findByEmail(dto.email);
|
|
if (existing) {
|
|
throw new ConflictException(
|
|
`Customer with email "${dto.email}" already exists`,
|
|
);
|
|
}
|
|
return this.customersRepository.create(dto);
|
|
}
|
|
|
|
findAll(): Promise<Customer[]> {
|
|
return this.customersRepository.findAll({ order: { name: "ASC" } });
|
|
}
|
|
|
|
async findById(id: string): Promise<Customer> {
|
|
const customer = await this.customersRepository.findById(id);
|
|
if (!customer) {
|
|
throw new NotFoundException(`Customer ${id} not found`);
|
|
}
|
|
return customer;
|
|
}
|
|
|
|
async update(id: string, dto: UpdateCustomerDto): Promise<Customer> {
|
|
await this.findById(id);
|
|
|
|
if (dto.email) {
|
|
const conflict = await this.customersRepository.findByEmail(dto.email);
|
|
if (conflict && conflict.id !== id) {
|
|
throw new ConflictException(
|
|
`Customer with email "${dto.email}" already exists`,
|
|
);
|
|
}
|
|
}
|
|
|
|
const updated = await this.customersRepository.update(id, dto);
|
|
if (!updated) {
|
|
throw new NotFoundException(`Customer ${id} not found`);
|
|
}
|
|
return updated;
|
|
}
|
|
|
|
async remove(id: string): Promise<void> {
|
|
await this.findById(id);
|
|
await this.customersRepository.softDelete(id);
|
|
}
|
|
}
|