「config.ts」の1つのファイルにすべての構成をセットアップし、それをConfigServiceにロードしてから、構成インターフェースを使用してそこから値を取得しようとしています。これが、私の .env ファイルと静的変数からの ENV 変数を持つ私の config.ts です。
UPD:この例でレポを作成
import { Config } from './config.interface';
const config: Config = {
typeorm: {
type: 'postgres',
host: process.env.DB_HOST,
port: +process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
synchronize: process.env.NODE_ENV !== 'prod',
logging: true,
entities: [User, RefreshToken],
},
};
export default () => config;
そして、ここに私のインターフェースがあります:
export interface Config {
typeorm: TypeOrmConfig;
}
export interface TypeOrmConfig {
type: string;
host: string;
port: number;
username: string;
password: string;
database: string;
synchronize: boolean;
logging: boolean;
entities: any[];
}
構成は app.module.ts の ConfigModule にロードされます
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.dev.env',
load: [config],
}),
}),
たとえば、この設定で TypeOrmModule をセットアップしたいとします。NestJs ドキュメントに基づく
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => {
const config = configService.get<TypeOrmConfig>('typeorm');
console.log(config);
return {
type: config.type,
host: config.host,
port: +config.port,
username: config.username,
password: config.password,
database: config.database,
synchronize: config.synchronize,
logging: config.logging,
entities: config.entities,
};
},
inject: [ConfigService],
}),
これが問題です。構成からの静的な値は問題ありませんが、私の ENV 変数はすべて未定義です。console.log の出力は次のとおりです。
{
type: 'postgres',
host: undefined,
port: NaN,
username: undefined,
password: undefined,
database: undefined,
synchronize: true,
logging: true,
entities: [
[class User extends CoreEntity],
[class RefreshToken extends CoreEntity]
]
}
未定義の ENV vars の何が問題なのかわかりません。説明と助けに感謝します