본문 바로가기
NestJS

NestJS - 서비스 및 컨트롤러

by Programmer.Junny 2025. 2. 20.
import { Injectable, NotFoundException } from '@nestjs/common';

export interface PostModel {
  id: number;
  author: string;
  title: string;
  content: string;
  likeCount: number;
  commentCount: number;
}

let posts: PostModel[] = [
  {
    id: 1,
    author: 'tester1',
    title: 'title1',
    content: 'content1',
    likeCount: 111,
    commentCount: 1111,
  },
  {
    id: 2,
    author: 'tester2',
    title: 'title2',
    content: 'content2',
    likeCount: 222,
    commentCount: 2222,
  },
  {
    id: 3,
    author: 'tester3',
    title: 'title3',
    content: 'content3',
    likeCount: 333,
    commentCount: 3333,
  },
];

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

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

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

    return post;
  }

  createPost(author: string, title: string, content: string) {
    const post: PostModel = {
      id: posts[posts.length - 1].id + 1,
      author,
      title,
      content,
      likeCount: 0,
      commentCount: 0,
    };

    posts = [...posts, post];

    return post;
  }

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

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

    if (author) {
      post.author = author;
    }

    if (title) {
      post.title = title;
    }

    if (content) {
      post.content = content;
    }

    posts = posts.map((prevPost) => (prevPost.id === id ? post : prevPost));

    return post;
  }

  deletePost(id: number) {
    const post = posts.find((post) => post.id === id);

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

    posts = posts.filter((post) => post.id !== id);

    return id;
  }
}

posts/posts.services.ts

서비스는 서버에서 실행될 핵심 로직들의 집합을 일컫는다.

위 로직에서는 임시적으로 'posts'라는 데이터들이 있다고 가정하고 진행한다.

PostsService 내에서 컨트롤러에서 호출될 로직들을 구현하고 있다.

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

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

  // 1) GET /posts
  //  모든 posts를 가져온다
  @Get()
  getPosts() {
    return this.postsService.getAllPosts();
  }

  // 2) GET /posts/:id
  // id에 해당되는 post를 가져온다.
  @Get(':id')
  getPost(@Param('id') id: string) {
    return this.postsService.getPostById(+id);
  }

  // 3) POST /posts
  //  post를 생성한다.
  @Post()
  postPosts(
    @Body('author') author: string,
    @Body('title') title: string,
    @Body('content') content: string,
  ) {
    return this.postsService.createPost(author, title, content);
  }

  // 4) PATCH /posts:id
  //  id에 해당되는 post를 변경한다.
  @Patch(':id')
  patchPost(
    @Param('id') id: string,
    @Body('author') author?: string,
    @Body('title') title?: string,
    @Body('content') content?: string,
  ) {
    return this.postsService.updatePost(+id, author, title, content);
  }

  // 5) DELETE /posts:id
  //  id에 해당되는 post를 삭제한다.
  @Delete(':id')
  deletePost(@Param('id') id: string) {
    return this.postsService.deletePost(+id);
  }
}

posts/posts.controller.ts

생성된 컨트롤러 내에 서비스 코드를 불러온다.

@Controller('posts')
export class PostsController {
// 1) GET /posts
  //  모든 posts를 가져온다
  @Get()
  getPosts() {
    return this.postsService.getAllPosts();
  }

posts로 Annotation된 컨트롤러 PostsController 내에 위와 같이 HTTP 메서드를 Annotation한 후 작업된 서비스 코드를 불러올 수 있다.

constructor(private readonly postsService: PostsService) {}

참고로 PostController 내에 생성자에서 의존성 주입되고 있는 PostsService와 같은 것들을 프로바이더(Provider)라고 불리운다.

'NestJS' 카테고리의 다른 글

Docker 이론  (0) 2025.02.24
NestJS - 제어의 역전과 의존성 주입  (0) 2025.02.20
NestJS - Postman 사용하기  (0) 2025.02.19
NestJS - Controller  (0) 2025.02.19
NestJS 라이프사이클  (0) 2025.02.19

최근댓글

최근글

skin by © 2024 ttuttak