[Nest.js 학습일기] Nest 프로젝트 생성, 구조
Nest 프로젝트 시작
Nest.js
는 강력한 CLI를 지원한다. 다음의 단축키로 프로젝트를 생성할 수 있다.
1
nest new server_name
Nest의 구성/구조
결론부터 말하면 React FSD 구조에서 widget들을 page의 tsx에 활용하는 것과 유사하다. 이게 무슨말이냐면 Frontend에서 컴포넌트를 구성하는 것 처럼 기능별로 이를 분리하고 이를 import 해서 사용한다고 생각하면 된다. 물론 import하는 것과 다소 차이가 있긴하다
Nest에선 service에서 함수를 정의하고 이를 controller에서 활용한다고 생각하면 된다. controller는 요청이 오면 어디로 가야하는지 routing 역할을 하고,service는 로직을 구현한다고 생각하면 된다. (기능의 분리)
더불어 app.service.ts에 모든 것을 몰아 넣을 수 없으니 경로별 Module을 생성하고 이를 활용한다.
Module생성 (CLI)
- 명령어 입력
1
2
nest g resource
'설정할 경로명'
- Rest API 선택
- CRUD entry point => 일단 no (추후 학습)
service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 5가지 (GET : 모든 게시물, 게시물 상세 & POST : 게시물 작성 & PUT : 게시물 수정 & DELETE)
import {Injectable, NotFoundException} from '@nestjs/common';
@Injectable()
export class PostsService {
getAllPosts() {
return posts;
}
getPostById(id: number) {
const post = posts.find(post => post.id === id);
if (!post) {
throw new NotFoundException(`Post with id ${id} not found`);
}
return post;
}
createPost(author: string, title: string, content: string) {
const post: Post = {
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(`Post with id ${id} not found`);
}
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(`Delete with id ${id} not found`);
}
posts = posts.filter(post => post.id !== +id);
return id;
}
}
controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import {Controller, Get, Post, NotFoundException, Param, Body, Put, Delete} from '@nestjs/common';
import { PostsService } from './posts.service';
@Controller('posts')
export class PostsController {
constructor(private readonly postsService: PostsService) {}
// 1) GET / posts => 모든 post를 가져온다.
// 2) GET / posts / :id => id에 해당하는 post를 가져온다.
// 3) POST / posts => post를 생성한다.
// 4) PUT / posts/:id => id에 해당하는 post를 변경한다.
// 5) DELETE / posts / :id => id에 해당하는 post를 삭제한다.
// 1.
@Get()
getPosts() {
return this.postsService.getAllPosts();
}
// 2.
@Get(':id')
getPost(@Param('id') id: string) {
return this.postsService.getPostById(+id);
}
// 3.
@Post()
postPosts(
@Body('author') author: string,
@Body('title') title: string,
@Body('content') content: string,
) {
return this.postsService.createPost(
author, title, content,
)
}
// 4.
@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,
)
}
// 5.
@Delete(':id')
deletePost(@Param('id') id: string) {
return this.postsService.deletePost(+id);
}
}
참고로 Rest API는 예외처리를 해야하는데, 이는 Nest.js
공식문서에서 확인할 수 있다. https://docs.nestjs.com/exception-filters#throwing-standard-exceptions
의존성 주입 / 제어의 역전 (Dependency Injection / Inversion of Control)
사실 이름만 거창하지 nest가 새로운 인스턴트를 생성하는 것을 Ioc Container을 활용해 의존성 주입을 도와준다~ 이말이다. 예시를 통해 확인해보자.
의존성 주입 에시
1
2
3
4
5
6
7
8
import {Controller, Get, Post, NotFoundException, Param, Body, Put, Delete} from '@nestjs/common';
import { PostsService } from './posts.service';
@Controller('posts')
export class PostsController {
constructor(private readonly postsService: PostsService) {}
// 1) GET / posts => 모든 post를 가져온다.
// ... 아래 이어서
해당 코드 (controller)는 service에 의존성을 가진다.
근데 이와 같은 과정이 인스턴스 생성 없이 진행이 가능한데 (module - provider에 등록된 것들), 이는 nest가 직접 기능을 제공하기 때문이다 (ioc container) 이와 같은 과정으로 개발자는 기능 구현에만 집중할 수 있다.
추가적으로 service 또한 Repository(entity 파일)에 의존성을 가진다. 즉 nest.js에서 전반적인 의존성 관계는 다음과 같다고 할 수 있다.
1
Controller -> Service -> Repository -> DB