Open1

NestJS 構築時のメモ

RinRin

DB接続

.env
MYSQL_ROOT_USER=xxx
MYSQL_ROOT_PASSWORD=xxx
MYSQL_USER=xxx
MYSQL_PASSWORD=xxx
MYSQL_DATABASE=xxx

通常のprocess.envなどを使わずに、ConfigService というモジュールが用意されているのでそちらを利用する

config.ts
import { ConfigService } from '@nestjs/config';
import { Injectable } from '@nestjs/common'
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm'

@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
    constructor(private configService :ConfigService) {}

    public createTypeOrmOptions():TypeOrmModuleOptions {
        return {
            type: 'mysql',
            host: 'localhost',
            port: 3306,
            username:  this.configService.get<string>('MYSQL_ROOT_USER'),
            password: this.configService.get<string>('MYSQL_ROOT_PASSWORD'),
            database: this.configService.get<string>('MYSQL_DATABASE'),
            entities: [], // use entites
            synchronize: true,
        }
    }
}

moduleに追加する。

app.module.ts
import { Module , NestModule, MiddlewareConsumer, Global} from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware'
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';

import { TypeOrmConfigService } from './data-source'
import { ConfigModule } from '@nestjs/config';
 
@Global()
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `.env`,
    }),
    TypeOrmModule.forRootAsync({
      useClass: TypeOrmConfigService // ここに入れる。
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('customer');
  }
}

classとしてのみConfigServiceは呼び出せないのでちょっとハマった。