* body 받는법
- 컨트롤러
@Post()
createPost(@Body() postData: { author: string; title: string; content:string; }){
return this.postsService.createPost(postData.author, postData.title, postData.content);
}
- 서비스
async createPost(author: string, title: string, content: string){
const post = this.postsRepository.create({
author: author,
title: title,
content: content,
likeCount:0,
commentCount:0,
});
const newPost = await this.postsRepository.save(post);
return newPost;
}
* patch 구현
- save를 이용해서, update를 구현하기를 권장함.
- 존재하는컬럼에 save를 날리면, 업데이트됨.
- :id 임에 주의! // /:id 아님
@Patch(':id')
updatePost(@Param('id') id:number, @Body() postData: { author: string; title: string; content:string; }){
return this.postsService.updatePost(id, postData.author, postData.title, postData.content);
}
async updatePost(postId: number, author: string, title: string, content: string) {
const post = await this.postsRepository.findOne({
where:{
id: postId,
}
});
if(!post){
throw new NotFoundException();
}
if(author){
post.author = author;
}
if(title){
post.title=title;
}
if(content){
post.content = content;
}
const newPost = await this.postsRepository.save(post);
return newPost;
}
* delete 구현
@Delete(':id')
deletePost(@Param('id') id:number){
return this.postsService.deletePost(id);
}
async deletePost(id: number) {
const post = await this.postsRepository.findOne({
where:{
id,
}
});
if(!post){
throw new NotFoundException();
}
await this.postsRepository.delete(id);
return id;
}
'JS > Nest.js' 카테고리의 다른 글
[Nest] typeorm 설정, 리포지토리 설정방법 (0) | 2024.09.18 |
---|---|
[Nest] enum => 값 제한 하기 (0) | 2024.09.18 |
[Nest] typeorm 설정, 모듈생성, 의존성주입, No metadata for "PostsModel" was found 문제해결 (0) | 2024.09.17 |
[Nest] Dependency Injection 의존성 주입 (0) | 2024.09.17 |
[Nest JS] 환경변수 설정 / configuration property is not defined 해결 / github 캐시 지우는법 (0) | 2024.08.19 |