Performance: ConfigModule setup
This affects the initial application startup time and memory usage by loading configuration settings efficiently.
import { ConfigModule } from '@nestjs/config'; import { Module } from '@nestjs/common'; @Module({ imports: [ConfigModule.forRoot({ isGlobal: true })], }) export class AppModule {}
import { readFileSync } from 'fs'; import { Injectable, Module } from '@nestjs/common'; @Injectable() export class ConfigService { private config; constructor() { this.config = JSON.parse(readFileSync('config.json', 'utf-8')); } get(key: string) { return this.config[key]; } } @Module({ providers: [ConfigService], exports: [ConfigService], }) export class ConfigModule {}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous config file read in service constructor | 0 | 0 | 0 | [X] Bad |
| ConfigModule.forRoot with async loading and global cache | 0 | 0 | 0 | [OK] Good |
ConfigModule in a NestJS application?ConfigModule globally in the root module?forRoot() with isGlobal: true.forFeature() is for scoped configs, register() and global() are not valid methods here.constructor(private configService: ConfigService) {}
getDbHost() {
return this.configService.get('DATABASE_HOST');
}getDbHost() return if DATABASE_HOST is set to "localhost" in the environment?get method returns the value of the environment variable if set, here 'localhost'.DATABASE_HOST is set to 'localhost', the method returns that string, not undefined or null.@Module({
imports: [ConfigModule.forRoot({ isGlobal: true })],
providers: [ConfigService],
})
export class AppModule {}isGlobal: true is set, ConfigService is automatically provided app-wide, no need to add it manually.custom.env using ConfigModule and make it global. Which setup is correct?envFilePath, and to make it global use isGlobal: true inside forRoot().envFileName and global are invalid option names; forFeature and register are not used for global config loading.Pass the test and this pattern moves unknown