728x90
nest CLI로 모듈 생성하기
// nest generate <schematic> <name> [options]
// nest g <schematic> <name> [options]
$ nest g mo cats
모듈명은 복수로 짓는 것을 권고한다고 한다.
// Controller 생성
nest g co cats
// Service 생성
nest g service cats
CLI로 모듈 뿐만 아니라 controller와 service도 편하게 생성할 수 있다.
캡슐화
// cats.module
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 {}
CatsService를 Cats모듈이 아닌 다른 모듈에서 사용을 하고자 한다면 exports로 보내줘야 한다.
The module encapsulates providers by default. This means that it's impossible to inject providers that are neither directly part of the current module nor exported from the imported modules. Thus, you may consider the exported providers from a module as the module's public interface, or API.
공식문서에 따르면 모듈은 프로바이더를 기본적으로 캡슐화시킨다. 캡슐화했기 때문에 현재 모듈의 일부가 아니거나 exported하지 않은 공급자는 주입할 수 없다는 의미다. 쉽게 말하면 다른 모듈을 공급자로 주입을 하려면 내보내기(export)를 해야한다는 말이다. 따라서 모듈로부터 export된 프로바이더는 일종의 API나 공개 인터페이스로 봐야 한다고 한다.
cats 서비스를 다른 app 모듈에서 사용해보기
// cats.service
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
hiServiceProduct() {
return 'hello guys:D';
}
}
캣츠 서비스를 하나 만들어주었다. 이것을 Cats 모듈이 아니라 app 모듈의 컨트롤러에서 사용해보자.
// app.controller
import { Body, Controller, Get, Param, Req } from '@nestjs/common';
import { AppService } from './app.service';
import { Request } from 'express';
import { CatsService } from './cats/cats.service';
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly catsService: CatsService,
) {}
@Get()
getHello(): string {
return this.catsService.hiServiceProduct();
}
}
catsService로부터 프로바이더를 주입받아서 getHello() 핸들러에서 사용했다. 이것이 가능하려면 appModule에에 CatsService를 provider로 등록해야 한다.
// cats.module
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 {}
cats모듈에서 export해주었기에 외부에서 cats모듈을 임포트하여 catsservice를 사용할 수 있다.
// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CatsModule } from './cats/cats.module';
import { CatsService } from './cats/cats.service';
@Module({
imports: [CatsModule],
controllers: [AppController],
providers: [AppService, CatsService],
})
export class AppModule {}
728x90
'Research > Nest.js' 카테고리의 다른 글
nestjs_filter로 에러 처리하기 (0) | 2023.04.04 |
---|---|
nestjs_logger 미들웨어 생성하여 주입해보기 (0) | 2023.04.04 |
nestjs_공급자(provider)와 DI(Dependency Injection) (0) | 2023.04.04 |
10. Nest.js_Database 읽기 (0) | 2023.02.07 |
09. Nest.js_ Database 준비 (0) | 2023.02.07 |
댓글