Skip to Content
BackendNestJs04-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
1
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common'
2
import { PostsService } from './posts.service'
3
4
@Controller('posts')
5
export class PostsController {
6
constructor(private readonly postsService: PostsService) {}
7
8
/*** 1) GET /posts
9
* 모든 post를 다 가져온다
10
*/
11
@Get()
12
getPosts() {
13
return this.postsService.getAllPosts()
14
}
15
16
/*** 2) GET /posts/:id
17
* id에 해당하는 post를 가져온다
18
* e.g. 11이라는 ID를 갖고있는 Post 하나를 가져온다.
19
*/
20
// @Param('id') 뜻 : 가져오는 파라미터의 이름은 id이다
21
@Get(':id')
22
getPost(@Param('id') id: string) {
23
return this.postsService.getPostById(+id)
24
}
25
26
/*** 3) POST /posts
27
* post를 생성한다
28
*/
29
@Post()
30
postPosts(
31
@Body('author') author: string, //
32
@Body('title') title: string,
33
@Body('content') content: string,
34
) {
35
return this.postsService.createPost(author, title, content)
36
}
37
38
/*** 4) PATCH /posts/:id
39
* id에 해당하는 post를 부분 변경한다
40
*/
41
@Patch(':id')
42
putPost(
43
@Param('id') id: string, //
44
@Body('author') author?: string, //
45
@Body('title') title?: string,
46
@Body('content') content?: string,
47
) {
48
return this.postsService.updatePost(+id, author, title, content)
49
}
50
51
/*** 5) DELETE /posts/:id
52
* id에 해당하는 post를 삭제한다
53
*/
54
@Delete(':id')
55
deletePost(@Param('id') id: string) {
56
return this.postsService.deletePost(+id)
57
}
58
}
posts.service.ts
1
import { Injectable, NotFoundException } from '@nestjs/common'
2
3
export interface PostModel {
4
id: number
5
author: string
6
title: string
7
content: string
8
likeCount: number
9
commentCount: number
10
}
11
12
let posts: PostModel[] = [
13
{
14
id: 1,
15
author: 'newjeans_official',
16
title: '뉴진스 민지',
17
content: '메이크업 고치고 있는 민지',
18
likeCount: 100000,
19
commentCount: 999999,
20
},
21
{
22
id: 2,
23
author: 'newjeans_official',
24
title: '뉴진스 혜린',
25
content: '노래 연습하고 있는 혜린',
26
likeCount: 100000,
27
commentCount: 999999,
28
},
29
{
30
id: 3,
31
author: 'blackpink_official',
32
title: '블랙핑크 로제',
33
content: '공연중인 로제',
34
likeCount: 100000,
35
commentCount: 999999,
36
},
37
]
38
39
@Injectable()
40
export class PostsService {
41
getAllPosts() {
42
return posts
43
}
44
45
getPostById(id: number) {
46
const post = posts.find(post => post.id === +id)
47
48
if (!post) {
49
throw new NotFoundException()
50
}
51
52
return post
53
}
54
55
createPost(author: string, title: string, content: string) {
56
const post = {
57
id: posts[posts.length - 1].id + 1,
58
author,
59
title,
60
content,
61
likeCount: 0,
62
commentCount: 0,
63
}
64
65
posts = [...posts, post]
66
67
return post
68
}
69
70
updatePost(postId: number, author: string, title: string, content: string) {
71
const post = posts.find(post => post.id === postId)
72
73
if (!post) {
74
throw new NotFoundException()
75
}
76
if (author) {
77
post.author = author
78
}
79
if (title) {
80
post.title = title
81
}
82
if (content) {
83
post.content = content
84
}
85
posts = posts.map(prevPost => (prevPost.id === postId ? post : prevPost))
86
87
return post
88
}
89
90
deletePost(postId: number) {
91
const post = posts.find(post => post.id === postId)
92
if (!post) {
93
throw new NotFoundException()
94
}
95
96
posts = posts.filter(post => post.id !== postId)
97
return postId
98
}
99
}