nestjs使用ConfgService和TypeOrmModule

时间:2018-09-29 16:15:36

标签: nestjs

我按照文档https://docs.nestjs.com/techniques/configuration

所述设置了ConfigService

如何与TypeOrmModule一起使用此服务?

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

2 个答案:

答案 0 :(得分:6)

请参见https://docs.nestjs.com/techniques/database 异步配置一章

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

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

答案 1 :(得分:0)

如果您想使用配置类ConfigService,请使用useClass并提供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集成文档:https://docs.nestjs.com/techniques/database#async-configuration

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