카테고리 없음

Nest 폴더구조

namu445 2022. 5. 27. 23:59

src폴더 아래에 nest 주요 파일

app.controller.ts 단일 루트 컨트롤러 graphQL을 사용할 때는 리졸버로 사용한다.
app.controller.spec.ts 유닛 테스트 컨트롤러
app.module.ts 루트 모듈 다른 모듈이나 컨트롤러 서비스 모델을 모아서 사용할 수 있게 하는 기능을 한다. 
app.service.ts 서비스를 작성하는 파일
main.ts app.js, index.js의 역할을 하는 파일 nest의 코어(express와 유사한 역할)를 임포트해서 제공하고 있으며 많은 역할을 app.module과 분담하고 있다.

Controller

  • request를 처리하고 클라이언트에 response를 전달합니다.
  • 컨트롤러는 여러 route(api와 같은)를 포함하고 request를 route로 전달합니다.
  • 데코레이터와 클래스를 이용해서 작성합니다.
  • validation pipe를 연결해서 입력값을 검증할 수 있습니다.
@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}


//리졸버이지만 크게 다르지 않다.
@Resolver()
export class BoardResolver {
  constructor(private readonly boardService: BoardService) {}

  @Query(() => String)
  getHello() {
    return this.boardService.aaa();
  }
}
  • api를 사용할 때 중복되는 경로는 데코레이터에 전달해서 그룹화 할 수 있습니다.
// ex) /cats 경로로 Get 요청
// 데코레이터에 엔드포인트 경로를 전달하면 모든 요청의 경로 마지막에 지정한 경로를 추가한다.
import { Controller, Get } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()//api 메소드
  findAll(): string {// 함수 (이름은 임의로)
    return 'This action returns all cats';
  }
}

//status 코드를 지정해서 보낼때
@Post()
@HttpCode(204)
create() {
  return 'This action adds a new cat';
}

Modules

  • 앱의 구조를 만드는데 사용합니다. 여러 자원을 모아 구성해서 다른 모듈로 전달하거나 연결하며 앱의 구조를 만들 수 있습니다.
  • 연관된 기능들을 캡슐화할 수 있습니다.

providers @Injector 데코레이터로 작성된 서비스들 , resolver, service 등 같은 그룹?에 속해있는 파일들
controllers 작성된 컨트롤러들
imports entity, 스키마, 다른 모듈에서 export한 파일들
exports providers에 등록된 파일들 중에서 다른 모듈에서 사용할 파일들
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
//연관된 것들을 모아서 캡슐화해서 제공합니다.
  controllers: [CatsController],
  providers: [CatsService],
  exports: [CatsService]
})
export class CatsModule {}

//작성된 모듈을 root모듈(app.module)에서 import하는 예시
import { Module } from '@nestjs/common';
import { CatsModule } from './cats/cats.module';

@Module({
  imports: [CatsModule],
})
export class AppModule {}

 

 

 

 

 

 

<참고>

https://docs.nestjs.com/first-steps

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com