iconsulting/packages/services/user-service/src/app.module.ts

83 lines
2.5 KiB
TypeScript

import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtModule } from '@nestjs/jwt';
import {
TenantContextService,
TenantContextMiddleware,
SimpleTenantFinder,
DEFAULT_TENANT_ID,
} from '@iconsulting/shared';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import { HealthModule } from './health/health.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['.env.local', '.env'],
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('POSTGRES_HOST', 'localhost'),
port: configService.get<number>('POSTGRES_PORT', 5432),
username: configService.get('POSTGRES_USER', 'iconsulting'),
password: configService.get('POSTGRES_PASSWORD'),
database: configService.get('POSTGRES_DB', 'iconsulting'),
entities: [__dirname + '/**/*.orm{.ts,.js}'],
synchronize: configService.get('NODE_ENV') === 'development',
}),
}),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get('JWT_SECRET'),
signOptions: {
expiresIn: configService.get('JWT_EXPIRES_IN', '7d'),
},
}),
global: true,
}),
// Health check
HealthModule,
UserModule,
AuthModule,
],
providers: [TenantContextService, SimpleTenantFinder],
})
export class AppModule implements NestModule {
constructor(
private readonly tenantContext: TenantContextService,
private readonly tenantFinder: SimpleTenantFinder,
) {}
configure(consumer: MiddlewareConsumer) {
const tenantMiddleware = new TenantContextMiddleware(
this.tenantContext,
this.tenantFinder,
{
allowDefaultTenant: true,
defaultTenantId: DEFAULT_TENANT_ID,
excludePaths: ['/health', '/health/*'],
},
);
consumer
.apply((req: any, res: any, next: any) => tenantMiddleware.use(req, res, next))
.exclude(
{ path: 'health', method: RequestMethod.GET },
{ path: 'health/(.*)', method: RequestMethod.ALL },
)
.forRoutes('*');
}
}