[코팩] NestJs Controller Service 분리해서 사용하기

Seong Hyeon Kim·2024년 2월 8일
0

NestJs

목록 보기
6/14

컨트롤러 파일

posts.controller.ts

import { Body, Controller, Delete, Get, NotFoundException, Param, Patch, Post, Put } from '@nestjs/common';
import { PostsService } from './posts.service';


@Controller('posts')
export class PostsController {
  constructor(private readonly postsService: PostsService) {}

  @Get()
  getPosts(){
    return this.postsService.getAllPosts();
  }

  @Get(':id')
  getPost(@Param('id') id:string){
    return this.postsService.getPostById(+id)
  }

  @Post()
  postPosts(
    @Body('author') author : string,
    @Body('title') title : string,
    @Body('content') content : string
  ){
    return this.postsService.createPost(
      author,title,content
    );
  }
  
  @Put(':id')
  putPost(
    @Param('id') id:string,
    @Body('author') author? : string,
    @Body('title') title? : string,
    @Body('content') content? : string
  ){
    return this.postsService.updatePost(
      +id,author,title,content
    )
  }

  @Delete(':id')
  deltePost(
    @Param('id') id:string
  ){
    return this.postsService.deletePost(+id)
  }

}

서비스 파일

posts.controller.ts

import { Injectable, NotFoundException } from '@nestjs/common';


export interface PostModel{
    id :number;
    author : string;
    title : string;
    content : string;
    likeCount : number;
    commentConut : number;
  }
  
  let posts : PostModel[] = [
    {
      id:1,
      author : 'newjeans_official',
      title : '뉴진스 민지',
      content : '메이크업 고치고 있는 민지',
      likeCount : 10000,
      commentConut : 2000
    },
  
    {
      id:2,
      author : 'newjeans_official',
      title : '뉴진스 하니',
      content : '춤연습을 하는 하니',
      likeCount : 10000,
      commentConut : 2000
    },
    
    {
      id:3,
      author : 'aespa_official',
      title : '에스파 윈터',
      content : '노래 연습중인 윈터',
      likeCount : 10000,
      commentConut : 2000
    }
  ]

@Injectable()
export class PostsService {
    getAllPosts(){
        return posts;
    }

    getPostById(id:number){
        const post = posts.find((post)=>post.id === +id)

        if(!post){
          throw new NotFoundException()
        }else{
          return post
        }
    }

    createPost(author:string, title:string, content:string){
        const post = {
            id : posts[posts.length -1].id +1,
            author,
            title,
            content,
            likeCount:0,
            commentConut:0
          }
      
          // 기존 포스트 리스트에 새롭게 만든 포스트들을 추가
          posts = [
            ...posts,
            post,
          ];
      
          // 결과값으로는 리소스를 최대한 줄이기 위해 생성된 포스트만 리턴값으로 제공
          return post
      
    }

    updatePost(postId:number,author:string, title:string, content:string){
        const post = posts.find((post)=>post.id === postId)

        if(!post){
        throw new NotFoundException()
        }

        if(author){
        post.author = author
        }

        if(title){
        post.title = title
        }

        if(content){
        post.content = content
        }

        // map 으로 id 체크 후 맞으면 변경
        posts = posts.map((prePost)=>prePost.id === postId ? post : prePost)

        return post;
    }

    deletePost(postId:number){
        const post = posts.find((post)=>post.id === postId)
    posts = posts.filter((post)=> post.id !== postId)
    
    if(!post) {
      throw new NotFoundException()
    }else{
      return `선택하신 ${postId}번 게시물이 삭제되었습니다`
    }
    
    }
}

profile
삽질도 100번 하면 요령이 생긴다. 부족한 건 경험으로 채우는 백엔드 개발자

0개의 댓글