67 lines
2.2 KiB
TypeScript
67 lines
2.2 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { EntityNotFoundError, Repository } from 'typeorm';
|
|
import { Department } from './entities/department.entity';
|
|
import { DepartmentCreateDto } from './dto/department-create.dto';
|
|
import { DepartmentUpdateDto } from './dto/department-update.dto';
|
|
import { PaginateQuery, Paginated, paginate } from 'nestjs-paginate';
|
|
|
|
@Injectable()
|
|
export class DepartmentService {
|
|
constructor(
|
|
private readonly logger: Logger,
|
|
@InjectRepository(Department)
|
|
private departmentsRepository: Repository<Department>,
|
|
) {}
|
|
|
|
create(departmentCreateDto: DepartmentCreateDto): Promise<Department> {
|
|
// Use Repository.create() will copy the values to destination object.
|
|
const department = this.departmentsRepository.create(departmentCreateDto);
|
|
return this.departmentsRepository.save(department);
|
|
}
|
|
|
|
findAll(query: PaginateQuery): Promise<Paginated<Department>> {
|
|
return paginate(query, this.departmentsRepository, {
|
|
relations: { staffs: true },
|
|
sortableColumns: ['id', 'name'],
|
|
// select: ['id', 'name', 'staffs.name'],
|
|
// searchableColumns: ['name', 'department.name'],
|
|
// filterableColumns: {
|
|
// 'home.pillows.color': [FilterOperator.EQ],
|
|
// },
|
|
});
|
|
|
|
// return this.departmentsRepository.find();
|
|
}
|
|
|
|
findOne(id: number): Promise<Department> {
|
|
return this.departmentsRepository.findOneOrFail({ where: { id } });
|
|
}
|
|
|
|
async update(
|
|
id: number,
|
|
departmentUpdateDto: DepartmentUpdateDto,
|
|
): Promise<void> {
|
|
await this.isExist(id);
|
|
await this.departmentsRepository.update({ id }, departmentUpdateDto);
|
|
}
|
|
|
|
async remove(id: number): Promise<void> {
|
|
await this.isExist(id);
|
|
await this.departmentsRepository.delete(id);
|
|
}
|
|
|
|
// Helper function: Check if the entity exist.
|
|
// If entity does not exsit, return the Promise.reject()
|
|
private async isExist(id: number): Promise<void> {
|
|
const cnt = await this.departmentsRepository.countBy({ id });
|
|
if (cnt > 0) {
|
|
return;
|
|
} else {
|
|
return Promise.reject(
|
|
new EntityNotFoundError(Department, { where: { id } }),
|
|
);
|
|
}
|
|
}
|
|
}
|