Develop/[NestJs]
[NestJs] Api 좀 더 Restful 하게 변경
HiSmith
2023. 6. 18. 13:37
반응형
거지같던 레거시..가 아니고 내 코드를 좀더 바꿨다.
(controller)
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Put, NotFoundException } from '@nestjs/common';
import { CorpService } from './corp.service';
import { JwtAuthGuard } from 'src/auth/auth-guard';
import { Corp } from './entities/corp.entity';
import { ApiTags, ApiOperation, ApiResponse, ApiQuery, ApiParam, ApiBody } from '@nestjs/swagger';
import { CorpReqDto } from './corp.req.dto';
@ApiTags('corp') // (옵션) 태그 추가
@Controller('corp')
export class CorpController {
constructor(private readonly corpService: CorpService) {}
@ApiOperation({ summary: '업체 조회' }) // (옵션) API 동작 설명
@ApiParam({
description: 'corp find by id',
name: 'id'
})
@Get(':id')
async findOne(@Param('id') id: number) : Promise<Corp>{
const corp = await this.corpService.findbyCorpId(id);
console.log(corp);
if(!corp){
throw new NotFoundException();
}
return corp;
}
@ApiOperation({ summary: '업체 정보 생성' })
@ApiParam({
description: 'corp find by id',
type: CorpReqDto,
name: 'post'
})
@Post('')
postCorp(@Body('corp') corpReqDto :CorpReqDto) : Promise<Corp>{
return this.corpService.saveCorp(corpReqDto);
}
@ApiOperation({ summary: '업체 정보 수정' }) @ApiParam({
description: 'update corp',
type: CorpReqDto,
name: 'put'
})
@Put(':id')
putCorp(@Body('corp') corpReqDto :CorpReqDto,@Param('id') id: number){
return this.corpService.putCorp(id,corpReqDto);
}
@ApiOperation({ summary: '업체 정보 삭제' }) @ApiParam({
description: 'delete corp',
name: 'delete'
})
@Delete(':id')
deleteCorp(@Param('id')id: number){
return this.corpService.deleteCorp(id);
}
}
(service)
import { Inject, Injectable } from '@nestjs/common';
import { CorpRepostiory } from './corp.repository';
import { Corp } from './entities/corp.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CorpReqDto } from './corp.req.dto';
import { Repository } from 'typeorm';
@Injectable()
export class CorpService {
constructor(
@InjectRepository(Corp)
private corpRepository : CorpRepostiory
){}
async findbyCorpId(id:number) :Promise<Corp> {
return await this.corpRepository.findOne(id);
}
async saveCorp(corpReqDto: CorpReqDto) : Promise<Corp>{
const corp = new Corp(corpReqDto)
return await this.corpRepository.save(corp);
}
async putCorp(id: number,corpReqDto: CorpReqDto) :Promise<void>{
const corp = new Corp(corpReqDto);
this.corpRepository.update(id,corp);
}
async deleteCorp(id: number){
await this.corpRepository.delete(id);
}
//업데이트시 반영해야하는 목록을 공통 정의한 함수
updateReqtoEntity(corpReqDto :CorpReqDto,corp :Corp) :Corp{
corp.name = corpReqDto.name;
return corp
}
}
(repository)
import { AbstractRepository, EntityRepository, Repository } from "typeorm";
import { Corp } from "./entities/corp.entity";
import {getRepository} from "typeorm";
import { CorpReqDto } from "./corp.req.dto";
@EntityRepository(Corp)
export class CorpRepostiory extends Repository<Corp>{
async findbyCorpId(id: number): Promise<Corp>{
const corp =
await getRepository(Corp)
.createQueryBuilder("corp")
.where("corp.id = :id",{id})
.getOne();
return corp;
}
}
위의 코드대로 구현된 동작 방식은 아래와 같다.
* (get)(delete)
url : corp/{id}
* (put)
url : corp/{id}
body : {"corp":{"name":"hi_smith3"}}
* (delete)
url : corp/{id}
좀 더 Restful하게 변경했고, 그냥 군더더기 없이 깔끔하게 nestjs를 적용했다.
뭔가 귀찮아서 미루던 작업을 한김에 정리를 했다고 볼 수 있다.
반응형