NestJS Using ConfigService with TypeOrmModule

允我心安 提交于 2020-02-02 13:38:30

问题


I set up a ConfigService as described in docs https://docs.nestjs.com/techniques/configuration

How can I use this service with the the TypeOrmModule?

TypeOrmModule.forRoot({
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'root',
  password: 'root',
  database: 'test',
  entities: [__dirname + '/**/*.entity{.ts,.js}'],
  synchronize: true,
}),

回答1:


See https://docs.nestjs.com/techniques/database Async Configuration chapter

import {ConfigService} from './config.service';
import {Module} from '@nestjs/common';
import {TypeOrmModule} from '@nestjs/typeorm';

@Module({
    imports: [
        TypeOrmModule.forRootAsync({
            imports: [ConfigModule],
            useFactory: (config: ConfigService) => config.get('database'),
            inject: [ConfigService],
        }),
    ],
})
export class AppModule {}



回答2:


If you'd like to use the configuration class ConfigService, use useClass and provide TypeOrmConfigService

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from './config/config/config.module';
import { TypeOrmConfigService } from './config/typeorm.config';
import { ConfigService } from './config/config/config.service';

@Module({
  imports: [
    ConfigModule,
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useClass: TypeOrmConfigService,
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

TypeORM Integration doc: https://docs.nestjs.com/techniques/database#async-configuration

Configuration: https://docs.nestjs.com/techniques/configuration#using-the-configservice



来源:https://stackoverflow.com/questions/52570212/nestjs-using-configservice-with-typeormmodule

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!