SlideShare a Scribd company logo
1 of 21
NestJS 101
임광규
시작하기 전에,
 여기서 다루지 않는 것들
 nodejs
 typescript
 express
 여기서 다루는 것들
 nestjs
 nestjs 설정
목차
기초
1. NestJS는?
2. 주요 특징
3. NestJS CLI 설치
4. 프로젝트 생성
5. HelloWorld
활용
1. OAS 설정
2. Validation 설정
3. Configuration 설정
4. Logger 설정
5. Session 설정
6. Helmet & cors 설정
7. HttpMoudle 설정
1. NestJS는?
 효율적이고 안정적이며, 확장가능한 Backend 애플리케이션 구축을 위한
node.js 프레임워크입니다.
2. 주요 특징
 완벽한 Typescript 지원
 에코 시스템 제공
(Express, HttpModule, TypeORM, Logging 등)
 Nest CLI Tool 제공
 문서화가 잘 되어 있음
 모듈 식 구조로 다른 라이브러리 사용에 유연
3. NestJS CLI 설치
 NestJS CLI 설치
 CLI Help
 CLI generate Help
$ npm install -g @nestjs/cli
$ nest --help
$ nest generate --help
4. 프로젝트 생성
 프로젝트 생성
$ nest new project-name
find . | grep -v .git | grep -v node_modules | sed -e
"s/[^-][^/]*// |/g" -e "s/|([^ ])/|-1/"
.
|-package-lock.json
|-src
| |-app.controller.spec.ts
| |-app.module.ts
| |-app.controller.ts
| |-app.service.ts
| |-main.ts
|-nest-cli.json
|-package.json
|-README.md
|-.eslintrc.js
|-.prettierrc
|-tsconfig.json
|-test
| |-jest-e2e.json
| |-app.e2e-spec.ts
|-tsconfig.build.json
생성후 디렉토리 구조는 오른쪽과 같음
(.git, node_modules은 제외함)
5. HelloWord!
• lahuman@LAPTOP-LF12DOA8:~/DEV/project-name$ npm run start
• > project-name@0.0.1 start /home/lahuman/DEV/project-name
• > nest start
• [Nest] 236 - 01/24/2021, 10:21:03 PM [NestFactory] Starting Nest application...
• [Nest] 236 - 01/24/2021, 10:21:03 PM [InstanceLoader] AppModule dependencies initialized +29ms
• [Nest] 236 - 01/24/2021, 10:21:03 PM [RoutesResolver] AppController {}: +2ms
• [Nest] 236 - 01/24/2021, 10:21:03 PM [RouterExplorer] Mapped {, GET} route +2ms
• [Nest] 236 - 01/24/2021, 10:21:03 PM [NestApplication] Nest application successfully started +1ms
기본적으로 3000 Port로 기동되며,
웹으로 접속 시 Hello World!를
보여줍니다.
Console
Web browser
활용
Swagger, Logger, HttpModule, Cors, Configuration 등의 설정 정보
1. OAS 설정
 관련 모듈 설치
 main.ts에 다음 설정 추가
$ npm install --save @nestjs/swagger swagger-ui-express
import { NestFactory } from '@nestjs/core’;
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger’;
import { AppModule } from './app.module’;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Cats example’)
.setDescription('The cats API description’)
.setVersion('1.0') .addTag('cats’)
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup(‘docs', app, document);
await app.listen(3000);
}
bootstrap();
 웹 화면
2. Validation-설정
 필요 모듈 설치
 Global Validation 설정
(main.ts 에 추가)
 app.Controller.ts
app.useGlobalPipes(new ValidationPipe());
$ npm I --save class-validator class-transformer
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsNotEmpty } from 'class-
validator';
export class UserDto {
@IsEmail()
@ApiProperty({description: "user Id by Email"
, required: true})
email: string;
@IsNotEmpty()
@ApiProperty({description: "user password", r
equired: true})
password: string;
}
@Post('valid')
testValid(@Body() userDto: UserDto){
return "pass valid!";
}
 DTO
2. Validation-Docs
 2-1 Swagger 요청
 2-2 Email 정보가 아닐 경우
 2-3. 모든 조건을 통과할 경우
3. Configuration-설정
 필수 모듈 설치
 app.module.ts – Global 설정으로 처리
$ npm I --save @nestjs/config
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller
';
import { AppService } from './app.service';
@Module({
imports: [ConfigModule.forRoot()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
3. Configuration – 사용 예
import { Body, Controller, Get, Post } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AppService } from './app.service';
import { UserDto } from './dto/User.dto';
@Controller()
export class AppController {
constructor(private readonly appService: AppService, private configService: ConfigService) { }
@Get()
getHello(): string {
return this.appService.getHello();
}
@Post('valid')
testValid(@Body() userDto: UserDto) {
// get an environment variable
const dbUser = this.configService.get<string>('DATABASE_USER');
// get a custom configuration value
const dbHost = this.configService.get<string>('DATABASE_PASSWORD');
return "pass valid! : " + dbUser + "/" + dbHost;
}
}
4. Logger 설정
 사용하려는 class 내부에 다음을 선언(예: app.controller.ts)
 method 내부에서 사용
 결과 Console
private readonly logger = new Logger(AppController.name);
this.logger.log(userDto);
5. session 설정
 필요 모듈 설치
 main.ts 에 session 설정 추가
$ npm i express-session
$ npm i -D @types/express-session
import * as session from 'express-session’;
// somewhere in your initialization file
app.use(
session({
secret: 'my-secret',
resave: false,
saveUninitialized: false,
}),
);
5. session 사용
 app.controller.ts
 Request는 express를 사용
 결과 :
import { Request } from 'express';
@Get('/visits')
findAll(@Req() req: Request): string {
req.session["visits"] = req.session["visits"]
? req.session["visits"] + 1 : 1;
return "My VISITS : " + req.session["visits"];
}
6. helmet & cors 설정
 helmet 모듈 설치
 helmet 모듈 사용(main.ts)
 cors 사용(main.ts)
$ npm i --save helmet
import * as helmet from 'helmet';
app.use(helmet());
app.enableCors();
7. HttpModule 사용
 사용 선언(예 : app.module.ts)
 사용 예 (app.controller.ts)
@Module({
imports: [ConfigModule.forRoot(), HttpModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
@Get('/httpTest')
async callMockHtt(): Promise<any> {
const res = await this.httpService.get('htt
p://jsonplaceholder.typicode.com/todos/1').toPr
omise();
return res.data;
}
전체 소스 보기
 https://github.com/lahuman/nestjs_101
참고 자료
 NestJS : https://nestjs.com
 NestJS Documents : https://docs.nestjs.com

More Related Content

What's hot

Nodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjsNodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjs기동 이
 
Cactiez 설치, 백업, 복구
Cactiez 설치, 백업, 복구Cactiez 설치, 백업, 복구
Cactiez 설치, 백업, 복구ajj007
 
Resource Handling in Spring MVC
Resource Handling in Spring MVCResource Handling in Spring MVC
Resource Handling in Spring MVCArawn Park
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나JeongHun Byeon
 
Zabbix haproxy configuration_guide
Zabbix haproxy configuration_guideZabbix haproxy configuration_guide
Zabbix haproxy configuration_guidesprdd
 
스프링군살없이세팅하기(The way to setting the Spring framework for web.)
스프링군살없이세팅하기(The way to setting the Spring framework for web.)스프링군살없이세팅하기(The way to setting the Spring framework for web.)
스프링군살없이세팅하기(The way to setting the Spring framework for web.)EunChul Shin
 
Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신Circulus
 
Airflow를 이용한 데이터 Workflow 관리
Airflow를 이용한  데이터 Workflow 관리Airflow를 이용한  데이터 Workflow 관리
Airflow를 이용한 데이터 Workflow 관리YoungHeon (Roy) Kim
 
Leadweb Nodejs
Leadweb NodejsLeadweb Nodejs
Leadweb Nodejs근호 최
 
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개beom kyun choi
 
Node.js 현재와 미래
Node.js 현재와 미래Node.js 현재와 미래
Node.js 현재와 미래JeongHun Byeon
 
Html5 web workers
Html5 web workersHtml5 web workers
Html5 web workersWoo Jin Kim
 
Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822병헌 정
 
막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)연웅 조
 
Spring boot-summary(part2-part3)
Spring boot-summary(part2-part3)Spring boot-summary(part2-part3)
Spring boot-summary(part2-part3)Jaesup Kwak
 
[115] clean fe development_윤지수
[115] clean fe development_윤지수[115] clean fe development_윤지수
[115] clean fe development_윤지수NAVER D2
 

What's hot (20)

Nodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjsNodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjs
 
Cactiez 설치, 백업, 복구
Cactiez 설치, 백업, 복구Cactiez 설치, 백업, 복구
Cactiez 설치, 백업, 복구
 
Resource Handling in Spring MVC
Resource Handling in Spring MVCResource Handling in Spring MVC
Resource Handling in Spring MVC
 
Node.js at OKJSP
Node.js at OKJSPNode.js at OKJSP
Node.js at OKJSP
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나
 
Zabbix haproxy configuration_guide
Zabbix haproxy configuration_guideZabbix haproxy configuration_guide
Zabbix haproxy configuration_guide
 
스프링군살없이세팅하기(The way to setting the Spring framework for web.)
스프링군살없이세팅하기(The way to setting the Spring framework for web.)스프링군살없이세팅하기(The way to setting the Spring framework for web.)
스프링군살없이세팅하기(The way to setting the Spring framework for web.)
 
Node.js 심화과정
Node.js 심화과정Node.js 심화과정
Node.js 심화과정
 
Flux 예제 분석 2
Flux 예제 분석 2Flux 예제 분석 2
Flux 예제 분석 2
 
Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신
 
Airflow를 이용한 데이터 Workflow 관리
Airflow를 이용한  데이터 Workflow 관리Airflow를 이용한  데이터 Workflow 관리
Airflow를 이용한 데이터 Workflow 관리
 
Leadweb Nodejs
Leadweb NodejsLeadweb Nodejs
Leadweb Nodejs
 
Node.js 기본과정
Node.js 기본과정Node.js 기본과정
Node.js 기본과정
 
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
 
Node.js 현재와 미래
Node.js 현재와 미래Node.js 현재와 미래
Node.js 현재와 미래
 
Html5 web workers
Html5 web workersHtml5 web workers
Html5 web workers
 
Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822
 
막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)
 
Spring boot-summary(part2-part3)
Spring boot-summary(part2-part3)Spring boot-summary(part2-part3)
Spring boot-summary(part2-part3)
 
[115] clean fe development_윤지수
[115] clean fe development_윤지수[115] clean fe development_윤지수
[115] clean fe development_윤지수
 

Similar to Nest js 101

Vue.js 기초 실습.pptx
Vue.js 기초 실습.pptxVue.js 기초 실습.pptx
Vue.js 기초 실습.pptxwonyong hwang
 
Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기Jiam Seo
 
Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발지수 윤
 
Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조Sangon Lee
 
Node.js의 도입과 활용
Node.js의 도입과 활용Node.js의 도입과 활용
Node.js의 도입과 활용Jin wook
 
Node.js and react
Node.js and reactNode.js and react
Node.js and reactHyungKuIm
 
Angular 2 rc5 조사
Angular 2 rc5 조사Angular 2 rc5 조사
Angular 2 rc5 조사Rjs Ryu
 
Internship backend
Internship backendInternship backend
Internship backendYein Sim
 
H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉
H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉
H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉KTH, 케이티하이텔
 
H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례
H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례
H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례KTH
 
반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게Sungju Jin
 
Android Google Cloud Message 설정
Android Google Cloud Message 설정Android Google Cloud Message 설정
Android Google Cloud Message 설정정호 이
 

Similar to Nest js 101 (20)

테스트
테스트테스트
테스트
 
Vue.js 기초 실습.pptx
Vue.js 기초 실습.pptxVue.js 기초 실습.pptx
Vue.js 기초 실습.pptx
 
Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기
 
Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발
 
One-day-codelab
One-day-codelabOne-day-codelab
One-day-codelab
 
Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조Android 기초강좌 애플리캐이션 구조
Android 기초강좌 애플리캐이션 구조
 
Node.js의 도입과 활용
Node.js의 도입과 활용Node.js의 도입과 활용
Node.js의 도입과 활용
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
 
Nodejs express
Nodejs expressNodejs express
Nodejs express
 
Angular 2 rc5 조사
Angular 2 rc5 조사Angular 2 rc5 조사
Angular 2 rc5 조사
 
Internship backend
Internship backendInternship backend
Internship backend
 
What's new in IE11
What's new in IE11What's new in IE11
What's new in IE11
 
H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉
H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉
H3 2011 ios5 새로운 기능들의 프로젝트 적용 사례_ios팀_김윤봉
 
H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례
H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례
H3 2011 iOS5 새로운 기능들의 프로젝트 적용 사례
 
Xe hack
Xe hackXe hack
Xe hack
 
Springmvc
SpringmvcSpringmvc
Springmvc
 
반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게
 
Android Google Cloud Message 설정
Android Google Cloud Message 설정Android Google Cloud Message 설정
Android Google Cloud Message 설정
 
Amazed by aws 2nd session
Amazed by aws 2nd sessionAmazed by aws 2nd session
Amazed by aws 2nd session
 
4-3. jquery
4-3. jquery4-3. jquery
4-3. jquery
 

More from Daniel Lim

내가 생각하는 개발자란?
내가 생각하는 개발자란?내가 생각하는 개발자란?
내가 생각하는 개발자란?Daniel Lim
 
개발자를 넘어 기술 리더로 가는 길을 읽고
개발자를 넘어 기술 리더로 가는 길을 읽고개발자를 넘어 기술 리더로 가는 길을 읽고
개발자를 넘어 기술 리더로 가는 길을 읽고Daniel Lim
 
스크럼 101
스크럼 101스크럼 101
스크럼 101Daniel Lim
 
nodejs_101.pdf
nodejs_101.pdfnodejs_101.pdf
nodejs_101.pdfDaniel Lim
 
피드백 시스템
피드백 시스템피드백 시스템
피드백 시스템Daniel Lim
 
12.context api
12.context api12.context api
12.context apiDaniel Lim
 
11.react router dom
11.react router dom11.react router dom
11.react router domDaniel Lim
 
9.component style
9.component style9.component style
9.component styleDaniel Lim
 
7.component life cycle
7.component life cycle7.component life cycle
7.component life cycleDaniel Lim
 
6.component repeat
6.component repeat6.component repeat
6.component repeatDaniel Lim
 
4.event handling
4.event handling4.event handling
4.event handlingDaniel Lim
 
3.component 101
3.component 1013.component 101
3.component 101Daniel Lim
 
Swagger? OAS? with NodeJS
Swagger? OAS? with NodeJSSwagger? OAS? with NodeJS
Swagger? OAS? with NodeJSDaniel Lim
 

More from Daniel Lim (20)

내가 생각하는 개발자란?
내가 생각하는 개발자란?내가 생각하는 개발자란?
내가 생각하는 개발자란?
 
개발자를 넘어 기술 리더로 가는 길을 읽고
개발자를 넘어 기술 리더로 가는 길을 읽고개발자를 넘어 기술 리더로 가는 길을 읽고
개발자를 넘어 기술 리더로 가는 길을 읽고
 
스크럼 101
스크럼 101스크럼 101
스크럼 101
 
nodejs_101.pdf
nodejs_101.pdfnodejs_101.pdf
nodejs_101.pdf
 
For You
For YouFor You
For You
 
피드백 시스템
피드백 시스템피드백 시스템
피드백 시스템
 
13.code split
13.code split13.code split
13.code split
 
12.context api
12.context api12.context api
12.context api
 
11.react router dom
11.react router dom11.react router dom
11.react router dom
 
9.component style
9.component style9.component style
9.component style
 
7.component life cycle
7.component life cycle7.component life cycle
7.component life cycle
 
8.hooks
8.hooks8.hooks
8.hooks
 
6.component repeat
6.component repeat6.component repeat
6.component repeat
 
4.event handling
4.event handling4.event handling
4.event handling
 
5.ref 101
5.ref 1015.ref 101
5.ref 101
 
3.component 101
3.component 1013.component 101
3.component 101
 
2.jsx 101
2.jsx 1012.jsx 101
2.jsx 101
 
1.react 101
1.react 1011.react 101
1.react 101
 
Swagger? OAS? with NodeJS
Swagger? OAS? with NodeJSSwagger? OAS? with NodeJS
Swagger? OAS? with NodeJS
 
CuKu V1.3
CuKu V1.3CuKu V1.3
CuKu V1.3
 

Nest js 101

  • 2. 시작하기 전에,  여기서 다루지 않는 것들  nodejs  typescript  express  여기서 다루는 것들  nestjs  nestjs 설정
  • 3. 목차 기초 1. NestJS는? 2. 주요 특징 3. NestJS CLI 설치 4. 프로젝트 생성 5. HelloWorld 활용 1. OAS 설정 2. Validation 설정 3. Configuration 설정 4. Logger 설정 5. Session 설정 6. Helmet & cors 설정 7. HttpMoudle 설정
  • 4. 1. NestJS는?  효율적이고 안정적이며, 확장가능한 Backend 애플리케이션 구축을 위한 node.js 프레임워크입니다.
  • 5. 2. 주요 특징  완벽한 Typescript 지원  에코 시스템 제공 (Express, HttpModule, TypeORM, Logging 등)  Nest CLI Tool 제공  문서화가 잘 되어 있음  모듈 식 구조로 다른 라이브러리 사용에 유연
  • 6. 3. NestJS CLI 설치  NestJS CLI 설치  CLI Help  CLI generate Help $ npm install -g @nestjs/cli $ nest --help $ nest generate --help
  • 7. 4. 프로젝트 생성  프로젝트 생성 $ nest new project-name find . | grep -v .git | grep -v node_modules | sed -e "s/[^-][^/]*// |/g" -e "s/|([^ ])/|-1/" . |-package-lock.json |-src | |-app.controller.spec.ts | |-app.module.ts | |-app.controller.ts | |-app.service.ts | |-main.ts |-nest-cli.json |-package.json |-README.md |-.eslintrc.js |-.prettierrc |-tsconfig.json |-test | |-jest-e2e.json | |-app.e2e-spec.ts |-tsconfig.build.json 생성후 디렉토리 구조는 오른쪽과 같음 (.git, node_modules은 제외함)
  • 8. 5. HelloWord! • lahuman@LAPTOP-LF12DOA8:~/DEV/project-name$ npm run start • > project-name@0.0.1 start /home/lahuman/DEV/project-name • > nest start • [Nest] 236 - 01/24/2021, 10:21:03 PM [NestFactory] Starting Nest application... • [Nest] 236 - 01/24/2021, 10:21:03 PM [InstanceLoader] AppModule dependencies initialized +29ms • [Nest] 236 - 01/24/2021, 10:21:03 PM [RoutesResolver] AppController {}: +2ms • [Nest] 236 - 01/24/2021, 10:21:03 PM [RouterExplorer] Mapped {, GET} route +2ms • [Nest] 236 - 01/24/2021, 10:21:03 PM [NestApplication] Nest application successfully started +1ms 기본적으로 3000 Port로 기동되며, 웹으로 접속 시 Hello World!를 보여줍니다. Console Web browser
  • 9. 활용 Swagger, Logger, HttpModule, Cors, Configuration 등의 설정 정보
  • 10. 1. OAS 설정  관련 모듈 설치  main.ts에 다음 설정 추가 $ npm install --save @nestjs/swagger swagger-ui-express import { NestFactory } from '@nestjs/core’; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger’; import { AppModule } from './app.module’; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('Cats example’) .setDescription('The cats API description’) .setVersion('1.0') .addTag('cats’) .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup(‘docs', app, document); await app.listen(3000); } bootstrap();  웹 화면
  • 11. 2. Validation-설정  필요 모듈 설치  Global Validation 설정 (main.ts 에 추가)  app.Controller.ts app.useGlobalPipes(new ValidationPipe()); $ npm I --save class-validator class-transformer import { ApiProperty } from '@nestjs/swagger'; import { IsEmail, IsNotEmpty } from 'class- validator'; export class UserDto { @IsEmail() @ApiProperty({description: "user Id by Email" , required: true}) email: string; @IsNotEmpty() @ApiProperty({description: "user password", r equired: true}) password: string; } @Post('valid') testValid(@Body() userDto: UserDto){ return "pass valid!"; }  DTO
  • 12. 2. Validation-Docs  2-1 Swagger 요청  2-2 Email 정보가 아닐 경우  2-3. 모든 조건을 통과할 경우
  • 13. 3. Configuration-설정  필수 모듈 설치  app.module.ts – Global 설정으로 처리 $ npm I --save @nestjs/config import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { AppController } from './app.controller '; import { AppService } from './app.service'; @Module({ imports: [ConfigModule.forRoot()], controllers: [AppController], providers: [AppService], }) export class AppModule {}
  • 14. 3. Configuration – 사용 예 import { Body, Controller, Get, Post } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { AppService } from './app.service'; import { UserDto } from './dto/User.dto'; @Controller() export class AppController { constructor(private readonly appService: AppService, private configService: ConfigService) { } @Get() getHello(): string { return this.appService.getHello(); } @Post('valid') testValid(@Body() userDto: UserDto) { // get an environment variable const dbUser = this.configService.get<string>('DATABASE_USER'); // get a custom configuration value const dbHost = this.configService.get<string>('DATABASE_PASSWORD'); return "pass valid! : " + dbUser + "/" + dbHost; } }
  • 15. 4. Logger 설정  사용하려는 class 내부에 다음을 선언(예: app.controller.ts)  method 내부에서 사용  결과 Console private readonly logger = new Logger(AppController.name); this.logger.log(userDto);
  • 16. 5. session 설정  필요 모듈 설치  main.ts 에 session 설정 추가 $ npm i express-session $ npm i -D @types/express-session import * as session from 'express-session’; // somewhere in your initialization file app.use( session({ secret: 'my-secret', resave: false, saveUninitialized: false, }), );
  • 17. 5. session 사용  app.controller.ts  Request는 express를 사용  결과 : import { Request } from 'express'; @Get('/visits') findAll(@Req() req: Request): string { req.session["visits"] = req.session["visits"] ? req.session["visits"] + 1 : 1; return "My VISITS : " + req.session["visits"]; }
  • 18. 6. helmet & cors 설정  helmet 모듈 설치  helmet 모듈 사용(main.ts)  cors 사용(main.ts) $ npm i --save helmet import * as helmet from 'helmet'; app.use(helmet()); app.enableCors();
  • 19. 7. HttpModule 사용  사용 선언(예 : app.module.ts)  사용 예 (app.controller.ts) @Module({ imports: [ConfigModule.forRoot(), HttpModule], controllers: [AppController], providers: [AppService], }) export class AppModule {} @Get('/httpTest') async callMockHtt(): Promise<any> { const res = await this.httpService.get('htt p://jsonplaceholder.typicode.com/todos/1').toPr omise(); return res.data; }
  • 20. 전체 소스 보기  https://github.com/lahuman/nestjs_101
  • 21. 참고 자료  NestJS : https://nestjs.com  NestJS Documents : https://docs.nestjs.com