티스토리 뷰

728x90

Nest를 공부하다가 이런 알아들을 수 없는 함수 때문에 코드 읽는 것이 힘들었고 어떤 것을 사용해야 할지 몰랐었다.

참고한 블로그에서 발견한 글, 완전 공감..


nestjs의 모듈 생김새

@Module({
  imports: [],
  controllers: [],
  providers: [],
})
export class AppModule {}
// src/common/common.module.ts

@Module({
  controllers: [],
  imports: [
    ConfigModule.forRoot({
      load: configs,
      isGlobal: true,
    }),
    MysqlModule,
    RedisModule,
  ],
})
export class CommonModule {}
@Module({
  imports:[
    TypeOrmModule.forFeature([
      Alarms, // entitie
      ClientAlarms, // entitie
      Counseling // entitie
    ]),
  ],
  providers: [AlarmsService,AlarmsBuilder],
  controllers: [AlarmsController]
})
export class AlarmsModule {}

 

forRoot 

you are expecting to configure a dynamic module once and reuse that configuration in multiple places (though possibly unknowingly as it's abstracted away). This is why you have one GraphQLModule.forRoot(), one TypeOrmModule.forRoot(), etc.

: 동적 모듈을 한번 구성하고 해당 구성을 여러 위치에서 재사용
뇌피셜에 의하면 위의 두번째 코드 블럭에서 ConfigModule은 Common.module.ts 파일에서 한번 구성하고,
다른 파일에서 import해서 사용한다.

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => {
        return {
          type: 'mysql',
		  ...
        } as TypeOrmModuleOptions;
      },
    }),
  ],
})
export class MysqlModule {}

 

forFeature

you are expecting to use the configuration of a dynamic module's forRoot but need to modify some configuration specific to the calling module's needs (i.e. which repository this module should have access to, or the context that a logger should use.)
All of these, usually, have their async counterparts as well, registerAsync, forRootAsync, and forFeatureAsync, that mean the same thing, but use Nest's Dependency Injection for the configuration as well.

: 루트용 동적 모듈의 구성을 사용할 예정이지만 호출 모듈의 필요에 따라 일부 구성을 수정해야한다.
자체 주입 토큰이 있는 동적 공급자를 생성하기 위해 사용한다.

예를 들어 TypeOrmModule을 살펴보자.

1. Mysql에서 TypeOrmModule.forRootAsync()로 DB 연동하여 커넥션을 생성한 이후

// src/common/common.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => {
        return {
		...
        } as TypeOrmModuleOptions;
      },
    }),
  ],
})
export class MysqlModule {}

 

2. 각 모듈에 사용하는 엔터티들을 지정해주어야 한다.
boards 모듈에서 Board라는 엔터티를 사용하겠다는 의미이다.
그리고 이 코드 덕분에 boards.service에 주입할 수 있다,

// src/modules/v1/boards/boards.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Board } from './entities/board.entities';
import { BoardsController } from './boards.controller';
import { BoardsService } from './boards.service';

@Module({
  imports: [TypeOrmModule.forFeature([Board])],
  controllers: [BoardsController],
  providers: [BoardsService],
})
export class BoardsModule {}


3. boards.service.ts 파일에서 Board 엔터티를 사용할 수 있다.

// src/modules/v1/boards/boards.service.ts

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UpdateBoardDto } from './dto/update-board.dto';
import { CreateBoardDto } from './dto/create-board.dto';
import { Board } from './entities/board.entities';
import { BoardStatus } from './board-status.enum';

@Injectable()
export class BoardsService {
  constructor(
    @InjectRepository(Board) private boardRepository: Repository<Board>,
  ) {}

  async getBoards(): Promise<Board[]> {
    return this.boardRepository.find();
  }
  
  ...
}



Reference
- https://velog.io/@sunrabbit123/Nest.js-%EC%A2%80-%EB%8D%94-%EC%9E%90%EC%84%B8%ED%95%9C-%EB%AA%A8%EB%93%88feat.-methods

 

Nest.js 좀 더 자세한 모듈

Nest 겉핥기식 블로그들만 있길래 중급자를 위한 더 자세한 Module에 관한 고찰들

velog.io

- https://velog.io/@sunrabbit123/Nest.js-%EC%A2%80-%EB%8D%94-%EC%9E%90%EC%84%B8%ED%95%9C-%EB%AA%A8%EB%93%88feat.-methods