安装
npm install --save @nestjs/typeorm typeorm mysql2
使用
由于数据库的信息是敏感信息所以使用configService.get()进行获取
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath:
os.type() == 'Linux' ? `/opt/.env` : join(__dirname, '..', `.env`),
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
//区分测试环境和生产环境
host:
process.env.NODE_ENV === 'development'
? configService.get('TEST_SERVICE_HOST')
: configService.get('DATABASE_HOST'),
port: configService.get('DATABASE_PORT'),
username: configService.get('DATABASE_USER'),
password: configService.get('DATABASE_PASSWORD'),
database: configService.get('DATABASE_DATABASE'),
entities: [User],
synchronize: true,
autoLoadEntities: true,
}),
inject: [ConfigService],
}),
AppModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}