npm i -g @nestjs/cli
nest <<< 잘 깔려있나 help 같은 명령어
nest new project-name
HINT
TSstrict
를 추가하고 싶다면--strict
flag를 같이 쓸 것
nest new project-name --strict
파일명 | 설명 |
---|---|
app.controller.ts | 단일 라우트를 가진 기본 컨트롤러. |
app.controller.spec.ts | 컨트롤러의 단위 테스트 파일. |
app.module.ts | 애플리케이션의 루트 모듈. |
app.service.ts | 단일 메서드를 가진 기본 서비스. |
main.ts | NestFactory 를 사용해 애플리케이션 인스턴스를 생성하는 엔트리 파일. |
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
// src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
/**
* Decorator
* nestjs를 사용할 때 데코레이터는 짝꿍 같은 존재
* 데코레이터는 클래스에 함수 기능을 추가할 수 있다.
*/
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
controller
, service
: controller는 route, service는 비지니스 로직을 뜻하겠군export
하고 있구나. import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
/**
* controller는 express.js의 controller/router같은 것
*/
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get() // same as Express GET route
getHello(): string {
return this.appService.getHello();
}
// 데코레이터는 항상 클래스 or 함수에 붙어있어야한다. (Convention)
@Get('/hello')
getHi(): string {
return this.appService.getHi();
}
}
controller
는 라우트의기능을 해주는거 같다. import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World! holy';
}
getHi(): string {
return 'Hello fuccking everyone';
}
}
injectable
뭔가를 주입하고 있구나 getHello()
, getHi()
함수의 값을 return
하고 있구나일단 맨 처음 주는 코드로 봤을 때 main.ts
에서 팩토리 패턴을 활용해서 모듈을 찍어낼 수 있겠다. 라는 생각이 든다.
그리고 해당 module.ts
는 controller
와 service
를 분리해서 작성하고 있다.
즉, 라우터와 비즈니스 로직을 분리해서 작성하고 있다.
간단한 구조라고 생각듬
$ nest g co movies
// src/movies.controller.ts
import { Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
@Controller('movies')
export class MoviesController {
@Get()
getAll() {
return 'this will return all movies';
}
@Get('/:id')
getOne(@Param('id') movieId: string) {
return `this will return one movie with the id : ${movieId}`;
}
@Post()
create() {
return 'this will create a movie';
}
@Delete('/:id')
remove(@Param('id') movieId: string) {
return `this will delete a movie with the id : ${movieId}`;
}
@Patch('/:id')
patch(@Param('id') movieId: string) {
return `this will update a movie with the id : ${movieId}`;
}
}
params, body, header, etc ...
)를 원하면 인자로 넣어서 요청을 해야한다.@Param
: 파라미터 요청