# nest cli 전역 설치
npm i -g @nestjs/cli
nest -v # 8.0.0
cd packages
# nest new {프로젝트 이름}
nest new backend
주의할점
- 현재 모노레포의 prettier 설정과 nest의 prettier설정이 충돌납니다.
- backend 폴더 내부에 있는 .prettierrc 삭제해주세요!
- nest의 eslintrc.js > plugins 에
prettier
추가해주시면 됩니다.
- nest 자체에서도 .git이 생성 되므로 삭제할것!
{
...
plugins: ["@typescript-eslint/eslint-plugin", "prettier"], // prettier 추가
...
}
module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
exports: [AppService]
})
// 해당 부분 내부에선 middleware, method 등 을 정의하여 적용할 수 있습니다.
export class AppModule {}
// --- 저는 AppService를 TestService에서 사용하고 싶습니다! ---
// test.service.ts
@Module({
imports: [AppModule], // AppService가 정의된 AppModule을 주입받음
controllers: [TestController],
providers: [TestService],
exports: []
})
export class TestModule {}
@Module()
이라는 데코레이터를 통해 해당 모듈을 구성하는 정보와 파일간 의존성을 관리합니다.
providers
: 해당 모듈에서 정의된 인스턴스화되어야하는 프로바이더 (service, strategy 등)
conrtollers
: 해당 모듈에서 정의된 인스턴스화 되어야하는 컨트롤러의 집합
import
: 해당 모듈에서 필요한 모듈의 집합 (다른 모듈에서 정의한 provider를 사용할 경우 imports 내부에 해당 provider 를 가지고 있는 모듈을 추가)
exports
: 선언시 다른 모듈에서 사용가능할 수 있도록 노출할 프로바이더 (service 등)
controller.ts
import { Controller, Get, Post } from "@nestjs/common";
import { TestService } from "./test.service";
// base point: /test
@Controller('test')
export class TestController {
constructor(private readonly testService: TestService) {}
// GET /test
@Get()
getHello(): string {
return this.testService.getHello();
}
// GET /test:id
@Get(':id')
getTest(): string {
return this.testService.getHello();
}
// POST /test
@Post('')
addTest(): string {
return this.testService.getHello();
}
}
// --------- express --------
app.get('/test', (req, res) => ...)
app.get('/test:id', (req, res) => ...)
app.post('/test', (req, res) => ...)
@Controller()
데코레이터를 통해 해당 controller의 라우터를 정의합니다.
@Controller()
내부 인자로 end point를 설정하여 해당 경로로 요청이 왔을때 정의된 controller를 실행하여 요청을 대한 응답을 실행합니다.
- controller 내부에 정의된
@Get
, @Post
둥 데코레이터를 통해 end point에 따라 일치하는 요청에 대한 처리를 진행합니다.