37 lines
1.3 KiB
TypeScript
37 lines
1.3 KiB
TypeScript
import { DynamicModule, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { TenantContextMiddleware } from './tenant-context.middleware';
|
|
import { SnakeNamingStrategy } from './snake-naming.strategy';
|
|
|
|
@Module({})
|
|
export class DatabaseModule implements NestModule {
|
|
configure(consumer: MiddlewareConsumer) {
|
|
consumer.apply(TenantContextMiddleware).forRoutes('*');
|
|
}
|
|
|
|
static forRoot(): DynamicModule {
|
|
return {
|
|
module: DatabaseModule,
|
|
imports: [
|
|
TypeOrmModule.forRootAsync({
|
|
inject: [ConfigService],
|
|
useFactory: (config: ConfigService) => ({
|
|
type: 'postgres',
|
|
host: config.get('DB_HOST', 'localhost'),
|
|
port: config.get<number>('DB_PORT', 5432),
|
|
username: config.get('DB_USERNAME', 'it0'),
|
|
password: config.get('DB_PASSWORD', 'it0_dev'),
|
|
database: config.get('DB_DATABASE', 'it0'),
|
|
autoLoadEntities: true,
|
|
synchronize: config.get('NODE_ENV') === 'development',
|
|
logging: config.get('DB_LOGGING', 'false') === 'true',
|
|
namingStrategy: new SnakeNamingStrategy(),
|
|
}),
|
|
}),
|
|
],
|
|
exports: [TypeOrmModule],
|
|
};
|
|
}
|
|
}
|