JS/Nest.js

[Nest] CRUD 구현, body 받는법

Mini_96 2024. 9. 17. 23:53

* 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;
}

포스트맨
db

 

* 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;
}

param은 @param으로 받을수있음
body는 @body로 파싱함

 

* 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;
}