Files
yunhaifinance/backend/src/modules/customers/customers.service.ts
T

65 lines
1.9 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Customer } from './customer.entity';
@Injectable()
export class CustomersService {
constructor(
@InjectRepository(Customer)
private customersRepository: Repository<Customer>,
) {}
async create(customerData: Partial<Customer>): Promise<Customer> {
const customer = this.customersRepository.create(customerData);
return this.customersRepository.save(customer);
}
async findAll(): Promise<Customer[]> {
return this.customersRepository.find();
}
async findOne(id: string): Promise<Customer> {
const customer = await this.customersRepository.findOne({ where: { id } });
if (!customer) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
return customer;
}
async update(id: string, customerData: Partial<Customer>): Promise<Customer> {
const customer = await this.findOne(id);
Object.assign(customer, customerData);
return this.customersRepository.save(customer);
}
async remove(id: string): Promise<void> {
const result = await this.customersRepository.delete(id);
if (result.affected === 0) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
}
async findWithProjects(id: string): Promise<Customer> {
const customer = await this.customersRepository.findOne({
where: { id },
relations: ['projects'],
});
if (!customer) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
return customer;
}
async findWithQuotations(id: string): Promise<Customer> {
const customer = await this.customersRepository.findOne({
where: { id },
relations: ['quotations'],
});
if (!customer) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
return customer;
}
}