nestjs_nomad_02.init nestjs

ohbin Kwon·2021년 9월 26일
0
  1. nestjs/cli 설치
sudo npm i -g @nestjs/cli
  1. 프로젝트 생성
nest new
  1. 데코레이터
    nestjs에서 가장 중요한 개념.
    @로 시작하며 class에 종속됨
    (니콜라스에 따르면 아이스크림에 토핑되는 초코칩 같은 존재)
@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
  1. 폴더 구조

main.ts: 시작점
app.module.ts: 루트 모듈
app.controller.ts : url을 가져오고, 함수를 실행(express의 라우터 같은 존재)
app.service.ts:

  1. app.controller.ts
  • @Get(get데코레이터) -> express의 get 라우터와 같은 역할
  • 함수, 클래스와 붙여서 사용해야함(엔터치지 말것)
@Controller()
export class AppController {

  @Get('/hello')
  sayhello(): string {
    return "hello everyone"
  }
}
  • nestjs가 모든 기능을 지원해주기 때문에 router를 설정할 필요없이 url을통해 함수만 실행시켜주면됨!

  • post, put 등 데코레이터를 이용해 다양한 통신이 가능함

  • 만약 @post를 사용해 잘못된 통신을 설정했다고해도 nestjs가 알아서 에러처리를 해줌

에러처리

  1. app.service.ts
import { Controller, Get, Post } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
  @Get('/hello')
  sayhello(): string {
    return "hello everyone"
  }
}
  • 데코레이터를 사용하면 통신이 가능한데 왜, service를 참조할까?
  • 바로, nestjs는 비즈니스 로직과 컨트롤러를 구분짓고싶어 하기 때문이다.
  • 따라서, 실제 함수, 비즈니스 로직은 service에 위치한다

app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello Nest!';
  }
  getHi(): string {
    return 'Hi Nest!'
  }
}

app.controller.ts

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
  @Get('/hello')
  sayhello(): string {
    return this.appService.getHi()
  }
}
profile
개발 로그

0개의 댓글

관련 채용 정보