🎉 berenickt 블로그에 온 걸 환영합니다. 🎉
Back
NestJs
01-NestJS 소개

1. NestJS 소개

nestjs-request-life-cycle

Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications.

NestJS는 효율적이고 스케일링이 쉬운 NodeJS 서버를 만드는 프레임워크이다.


It uses progressive JavaScript, is built with and fully supports TypeScript

차세대 javascript를 사용하며, Typescript로 만들어졌으면 Typescript를 지원한다.

(yet still enables developers to code in pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).


Under the hood, Nest makes use of robust HTTP Server frameworks like Express (the default) and optionally can be configured to use Fastify as well!

NextJS는 Express같은 견고한 HTTP 서버 프레임워크를 사용하고 있으며 원한다면 Fastify를 대신 사용할 수도 있다.


Nest provides an out-of-the-box application architecture which allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications.

NestJS는 자체적으로 서버 아키텍처를 제공해준다. 그래서 테스트하기 쉽고, 디커플링이 잘 돼있고, 유지보수가 편한 서버를 제작하게 해준다.

— cf. Nest.js 공식문서 (https://docs.nestjs.com/)


2. Mac 환경설정

1
$ node -v
2
v18.17.1
3
4
$ npm -v
5
9.6.7
6
7
$ sudo corepack enable
8
Password:
9
10
$ npm -g install pnpm
11
$ pnpm --version
12
9.4.0
13
14
$ yarn --version
15
1.22.21
16
17
$ yarn --version
18
1.22.21
19
20
$ sudo npm i -g @nestjs/cli

3. 기본 Node.js 서버

1
// HTTP 모듈을 가져옵니다.
2
const http = require('http')
3
4
// 서버를 실행할 호스트를 지정 localhost -> 127.0.0.1 -> 서버를 실행한 컴퓨터
5
const host = 'localhost'
6
7
// 서버가 사용할 포트를 지정
8
const port = 3000
9
10
/** HTTP 서버를 생성
11
* req -> request -> 요청
12
* res -> response -> 응답
13
*/
14
const server = http.createServer((req, res) => {
15
// 응답의 상태 코드와 콘텐츠 유형을 설정
16
res.writeHead(200, { 'Content-Type': 'text/html' })
17
// 응답으로 HTML을 보낸다.
18
res.end('<h1>Hello World</h1>')
19
})
20
21
// 서버를 실행합니다.
22
server.listen(port, host, () => {
23
// 서버가 실행 중임을 콘솔에 기록합니다.
24
console.log('server running on http://localhost:3000')
25
})

3.1 path별로 다른 응답 반환

1_server.js
1
const http = require('http')
2
const url = require('url')
3
4
const host = 'localhost'
5
const port = 3000
6
7
const server = http.createServer((req, res) => {
8
const path = url.parse(req.url).pathname
9
10
if (path === '/') {
11
res.writeHead(200, { 'Content-Type': 'text/html' })
12
res.end('<h1>Home Page</h1>')
13
} else if (path === '/post') {
14
res.writeHead(200, { 'Content-Type': 'text/html' })
15
res.end('<h1>Post Page</h1>')
16
} else if (path === '/user') {
17
res.writeHead(200, { 'Content-Type': 'text/html' })
18
res.end('<h1>User Page</h1>')
19
} else {
20
res.writeHead(200, { 'Content-Type': 'text/html' })
21
res.end('<h1>404 Page Not Found!</h1>')
22
}
23
})
24
25
server.listen(port, host, () => {
26
console.log('server running on http://localhost:3000')
27
})

3.2 Express로 REST API 구현

1
yarn init -y
2
yarn add express

express를 추가한다.

2_server.js
1
// Express 모듈을 가져옵니다.
2
const express = require('express')
3
4
// Express 객체를 생성합니다.
5
const app = express()
6
7
/** 종류
8
* app.get()
9
* app.post()
10
* app.delete()
11
* app.put()
12
*/
13
14
app.get('/', (req, res) => {
15
res.send('<h1>Home Page</h1>')
16
})
17
18
app.get('/post', (req, res) => {
19
res.send('<h1>Post Page</h1>')
20
})
21
22
app.get('/user', (req, res) => {
23
res.send('<h1>User Page</h1>')
24
})
25
26
app.use((req, res) => {
27
res.status(404).send('<h1>404 Page Not Found!</h1>')
28
})
29
30
// 서버를 시작합니다.
31
app.listen(3000, () => {
32
console.log('server running on http://localhost:3000')
33
})

node로 위 코드를 실행한다. 3.1절에서 express없이 쓴 코드와 비교해보면 훨씬 간단해진 것을 볼 수 있다.


3.3 NestJS로 Hello World

nest라고 명령어를 치면 도움말이 나온다.

1
$ nest
2
Usage: nest <command> [options]
3
4
Options:
5
-v, --version Output the current version.
6
-h, --help Output usage information.
7
8
Commands:
9
new|n [options] [name] Generate Nest application.
10
build [options] [app] Build Nest application.
11
start [options] [app] Run Nest application.
12
info|i Display Nest project details.
13
add [options] <library> Adds support for an external library to your project.
14
generate|g [options] <schematic> [name] [path] Generate a Nest element.
15
Schematics available on @nestjs/schematics collection:
16
┌───────────────┬─────────────┬──────────────────────────────────────────────┐
17
name │ alias │ description │
18
application │ application │ Generate a new application workspace │
19
class │ cl │ Generate a new class │
20
configuration │ config │ Generate a CLI configuration file │
21
controller │ co │ Generate a controller declaration │
22
decorator │ d │ Generate a custom decorator │
23
filter │ f │ Generate a filter declaration │
24
gateway │ ga │ Generate a gateway declaration │
25
guard │ gu │ Generate a guard declaration │
26
interceptor │ itc │ Generate an interceptor declaration │
27
interface │ itf │ Generate an interface │
28
library │ lib │ Generate a new library within a monorepo │
29
middleware │ mi │ Generate a middleware declaration │
30
module │ mo │ Generate a module declaration │
31
pipe │ pi │ Generate a pipe declaration │
32
provider │ pr │ Generate a provider declaration │
33
resolver │ r │ Generate a GraphQL resolver declaration │
34
resource │ res │ Generate a new CRUD resource │
35
service │ s │ Generate a service declaration │
36
sub-app │ app │ Generate a new application within a monorepo │
37
└───────────────┴─────────────┴──────────────────────────────────────────────┘

nest로 새 서버를 만들어보자

1
nest new nestjs_server
2
3
# yarn 선택
4
# 해당 폴더 위치로 이동

app.controller.ts 파일을 수정해줍니다.

app.controller.ts
1
import { Controller, Get } from '@nestjs/common'
2
import { AppService } from './app.service'
3
4
@Controller()
5
export class AppController {
6
constructor(private readonly appService: AppService) {}
7
8
@Get()
9
getHome() {
10
return 'Home Page'
11
}
12
13
@Get('post')
14
getPost() {
15
return 'Post Page'
16
}
17
18
@Get('user')
19
getUser() {
20
return 'User Page'
21
}
22
}