如何在 NestJS 中配置没有'process.env'和值提前未知的 TypeORM 模块?



通过装饰器配置TypeOrmModule的典型示例:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [],
autoLoadEntities: true, // Must be only on local development mode
synchronize: true,
}),
],
})
export class AppModule {}

所有设置都已硬编码。如果我们事先不知道hostportautoLoadEntities标志所依赖的环境名称等,该怎么办"提前";是指";当decorator内部的静态字段和值已被解析时,但当然,所有配置的拾取将在await NestFactory.create()之前完成。

import { NestFactory } from "@nestjs/core";
import type { NestExpressApplication } from "@nestjs/platform-express";
import Path from "path";
import { Logger } from "@yamato-daiwa/es-extensions";
import { ConsoleCommandsParser } from "@yamato-daiwa/es-extensions-nodejs";

(async function runApplication(): Promise<void> {
const configurationFromConsoleCommand: ConsoleCommandsParser.ParsedCommand<ConsoleLineInterface.ParsedArguments> =
ConsoleCommandsParser.parse(process.argv, ConsoleLineInterface.specification);
const normalizedConfiguration: NormalizedConfiguration = ConfigurationNormalizer.normalize({
configurationFromConsoleCommand
});
ConfigurationRepresentative.initialize(normalizedConfiguration);
// The preparing of the configuration is complete
const nestJS_Application: NestExpressApplication =
await NestFactory.create<NestExpressApplication>(NestJS_ApplicationRootModule);
await nestJS_Application.listen(normalizedConfiguration.HTTP_Port);
})().
catch((error: unknown): void => {
Logger.logError({
errorType: "ServerStartingFailedError",
title: "Server starting failed",
description: "The error occurred during starting of server",
occurrenceLocation: "runApplication()",
caughtError: error
});
});

一种方法是使用环境变量(process.env.XXX(。然而,它违反了条件";事先未知";决不能是唯一的解决方案。

type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',

这些属性不能未定义或未知,您必须首先配置它们

import { ConfigModule, ConfigService } from '@nestjs/config';
@Global()
@Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('DATABASE_HOST'),
port: configService.get<number>('DATABASE_PORT'),
username: configService.get('DATABASE_USER'),
password: configService.get('DATABASE_PASSWORD'),
database: configService.get('DATABASE_DB'),
schema: configService.get('DATABASE_SCHEMA'),
synchronize: !!configService.get<boolean>('DATABASE_SYNCRONIZE'),
logging: false, //!!configService.get<boolean>('DATABASE_LOGGING'),
autoLoadEntities: true,
}),
inject: [ConfigService],
}),
],
})

最新更新