97 lines
2.7 KiB
TypeScript
97 lines
2.7 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { EntityNotFoundError, Repository } from 'typeorm';
|
|
import { Staff } from './entities/staff.entity';
|
|
import { StaffCreateDto } from './dto/staff-create.dto';
|
|
import { StaffUpdateDto } from './dto/staff-update.dto';
|
|
import {
|
|
FilterOperator,
|
|
FilterSuffix,
|
|
PaginateQuery,
|
|
Paginated,
|
|
paginate,
|
|
} from 'nestjs-paginate';
|
|
|
|
@Injectable()
|
|
export class StaffsService {
|
|
constructor(
|
|
private readonly logger: Logger,
|
|
@InjectRepository(Staff)
|
|
private staffsRepository: Repository<Staff>,
|
|
) {}
|
|
|
|
create(staffCreateDto: StaffCreateDto): Promise<Staff> {
|
|
// Use Repository.create() will copy the values to destination object.
|
|
const staff = this.staffsRepository.create(staffCreateDto);
|
|
return this.staffsRepository.save(staff);
|
|
}
|
|
|
|
findAll(query: PaginateQuery): Promise<Paginated<Staff>> {
|
|
return paginate(query, this.staffsRepository, {
|
|
// loadEagerRelations: true,
|
|
// relations: { department: true, contract: true },
|
|
relations: ['contract', 'department'],
|
|
// sortableColumns: ['id', 'name', 'staffCode', 'department.name'],
|
|
sortableColumns: ['id', 'name', 'department.name'],
|
|
select: [
|
|
'id',
|
|
'name',
|
|
'staffCode',
|
|
'department.id',
|
|
'department.name',
|
|
'contract.id',
|
|
'contract.title',
|
|
'contract.details',
|
|
],
|
|
// searchableColumns: ['name', 'department.name'],
|
|
// filterableColumns: {
|
|
// 'department.name': [
|
|
// FilterOperator.EQ,
|
|
// FilterOperator.ILIKE,
|
|
// FilterSuffix.NOT,
|
|
// ],
|
|
// },
|
|
});
|
|
// return this.staffsRepository.find({
|
|
// relations: {
|
|
// department: true,
|
|
// },
|
|
// select: {
|
|
// id: true,
|
|
// name: true,
|
|
|
|
// departmentId: false,
|
|
// department: {
|
|
// id: false,
|
|
// name: true,
|
|
// },
|
|
// },
|
|
// });
|
|
}
|
|
|
|
findOne(id: number): Promise<Staff> {
|
|
return this.staffsRepository.findOneOrFail({ where: { id } });
|
|
}
|
|
|
|
async update(id: number, staffUpdateDto: StaffUpdateDto): Promise<void> {
|
|
await this.isExist(id);
|
|
await this.staffsRepository.update({ id }, staffUpdateDto);
|
|
}
|
|
|
|
async remove(id: number): Promise<void> {
|
|
await this.isExist(id);
|
|
await this.staffsRepository.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.staffsRepository.countBy({ id });
|
|
if (cnt > 0) {
|
|
return;
|
|
} else {
|
|
return Promise.reject(new EntityNotFoundError(Staff, { where: { id } }));
|
|
}
|
|
}
|
|
}
|