78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
import {
|
|
Controller,
|
|
Get,
|
|
Post,
|
|
Body,
|
|
Patch,
|
|
Param,
|
|
Delete,
|
|
NotFoundException,
|
|
HttpCode,
|
|
BadRequestException,
|
|
} from '@nestjs/common';
|
|
import { ApiResponse } from '@nestjs/swagger';
|
|
import { StaffsService } from './staffs.service';
|
|
import { Staff } from './entities/staff.entity';
|
|
import { StaffCreateDto } from './dto/staff-create.dto';
|
|
import { StaffUpdateDto } from './dto/staff-update.dto';
|
|
import { EntityNotFoundError } from 'typeorm';
|
|
import { Paginate, PaginateQuery, Paginated } from 'nestjs-paginate';
|
|
|
|
@Controller()
|
|
export class StaffsController {
|
|
constructor(private readonly staffsService: StaffsService) {}
|
|
|
|
private handleEntityNotFoundError(id: number, e: Error) {
|
|
if (e instanceof EntityNotFoundError) {
|
|
throw new NotFoundException(`Not found: id=${id}`);
|
|
} else {
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
@Get()
|
|
@ApiResponse({ type: [Staff] })
|
|
findAll(@Paginate() query: PaginateQuery): Promise<Paginated<Staff>> {
|
|
return this.staffsService.findAll(query);
|
|
}
|
|
|
|
@Get(':id')
|
|
@ApiResponse({ type: Staff })
|
|
async findOne(@Param('id') id: number): Promise<Staff | null> {
|
|
// NOTE: the + operator returns the numeric representation of the object.
|
|
return this.staffsService.findOne(+id).catch((err) => {
|
|
this.handleEntityNotFoundError(id, err);
|
|
return null;
|
|
});
|
|
}
|
|
|
|
@Post()
|
|
@ApiResponse({ type: [Staff] })
|
|
create(@Body() staffCreateDto: StaffCreateDto) {
|
|
return this.staffsService.create(staffCreateDto);
|
|
}
|
|
|
|
@Patch(':id')
|
|
// Status 204 because no content will be returned
|
|
@HttpCode(204)
|
|
async update(
|
|
@Param('id') id: number,
|
|
@Body() staffUpdateDto: StaffUpdateDto,
|
|
): Promise<void> {
|
|
if (Object.keys(staffUpdateDto).length === 0) {
|
|
throw new BadRequestException('Request body is empty');
|
|
}
|
|
await this.staffsService.update(+id, staffUpdateDto).catch((err) => {
|
|
this.handleEntityNotFoundError(id, err);
|
|
});
|
|
}
|
|
|
|
@Delete(':id')
|
|
@HttpCode(204)
|
|
async remove(@Param('id') id: number): Promise<void> {
|
|
await this.staffsService.remove(+id).catch((err) => {
|
|
this.handleEntityNotFoundError(id, err);
|
|
});
|
|
}
|
|
}
|