04-Service
1. Service 파일의 역할
txt
1유저(client)가 요청 --> controller ---> service
controller: 가장 맨 앞에서 클라이언트의 요청을 받는 역할- 받은 요청을 service에서 작성한 함수로 라우팅만 해주는 역할
- controller는 요청을 처리하기 위해 많은 것들이 필요하기에,
- 이 많은것들을 모두 controller에서 구현하기 보다, 그 기능 하나하나를 쪼개서 service 단위로 분할한다.
- 분할된 서비스나 리포지토리, 팩토리, 헬퍼 등을 Provider라고 하며, NestJS에서는 service를 Provider로 사용한다.
- 이런 Provider들을 controller에서 사용할 수 있게 의존성을 주입해서 사용한다.
- Provider는 module파일에서 등록 후 사용이 가능히디.
module: module은 밀접하게 관련된 기능의 집합- 일반적으로 module은 기능별로 만들어짐 (e.g. user, chat, order, …)
- 같은 기능에 해당하는 것들은 하나의 module 폴더 안에 넣어서 사용
- UserController, UserService, UserEntity …같은 것은 User에 관한 기능이기에 userModule 안에 넣어줌
- module은 기본적으로 싱글 톤이므로 여러 모듈간에 쉽게 자원을 공유할 수 있음
service: 각 요청의 기능들의 논리를 작성하는 부분- e.g. DB안에서 데이터를 가져오거나, 새로운 데이터 생성 시, 생성한 게시판 정보를 넣어주는 등의 로직을 처리
2. Service로 모든 로직 옮기기
posts.controller.ts
1import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common'2import { PostsService } from './posts.service'34@Controller('posts')5export class PostsController {6constructor(private readonly postsService: PostsService) {}78/*** 1) GET /posts9* 모든 post를 다 가져온다10*/11@Get()12getPosts() {13return this.postsService.getAllPosts()14}1516/*** 2) GET /posts/:id17* id에 해당하는 post를 가져온다18* e.g. 11이라는 ID를 갖고있는 Post 하나를 가져온다.19*/20// @Param('id') 뜻 : 가져오는 파라미터의 이름은 id이다21@Get(':id')22getPost(@Param('id') id: string) {23return this.postsService.getPostById(+id)24}2526/*** 3) POST /posts27* post를 생성한다28*/29@Post()30postPosts(31@Body('author') author: string, //32@Body('title') title: string,33@Body('content') content: string,34) {35return this.postsService.createPost(author, title, content)36}3738/*** 4) PATCH /posts/:id39* id에 해당하는 post를 부분 변경한다40*/41@Patch(':id')42putPost(43@Param('id') id: string, //44@Body('author') author?: string, //45@Body('title') title?: string,46@Body('content') content?: string,47) {48return this.postsService.updatePost(+id, author, title, content)49}5051/*** 5) DELETE /posts/:id52* id에 해당하는 post를 삭제한다53*/54@Delete(':id')55deletePost(@Param('id') id: string) {56return this.postsService.deletePost(+id)57}58}
posts.service.ts
1import { Injectable, NotFoundException } from '@nestjs/common'23export interface PostModel {4id: number5author: string6title: string7content: string8likeCount: number9commentCount: number10}1112let posts: PostModel[] = [13{14id: 1,15author: 'newjeans_official',16title: '뉴진스 민지',17content: '메이크업 고치고 있는 민지',18likeCount: 100000,19commentCount: 999999,20},21{22id: 2,23author: 'newjeans_official',24title: '뉴진스 혜린',25content: '노래 연습하고 있는 혜린',26likeCount: 100000,27commentCount: 999999,28},29{30id: 3,31author: 'blackpink_official',32title: '블랙핑크 로제',33content: '공연중인 로제',34likeCount: 100000,35commentCount: 999999,36},37]3839@Injectable()40export class PostsService {41getAllPosts() {42return posts43}4445getPostById(id: number) {46const post = posts.find(post => post.id === +id)4748if (!post) {49throw new NotFoundException()50}5152return post53}5455createPost(author: string, title: string, content: string) {56const post = {57id: posts[posts.length - 1].id + 1,58author,59title,60content,61likeCount: 0,62commentCount: 0,63}6465posts = [...posts, post]6667return post68}6970updatePost(postId: number, author: string, title: string, content: string) {71const post = posts.find(post => post.id === postId)7273if (!post) {74throw new NotFoundException()75}76if (author) {77post.author = author78}79if (title) {80post.title = title81}82if (content) {83post.content = content84}85posts = posts.map(prevPost => (prevPost.id === postId ? post : prevPost))8687return post88}8990deletePost(postId: number) {91const post = posts.find(post => post.id === postId)92if (!post) {93throw new NotFoundException()94}9596posts = posts.filter(post => post.id !== postId)97return postId98}99}