Complete the code to import the ConfigModule in a NestJS application.
import { Module } from '@nestjs/common'; import { [1] } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot()], }) export class AppModule {}
The ConfigModule is the NestJS module used for configuration management. Importing it allows the app to load environment variables and config files.
Complete the code to access a configuration value using ConfigService.
import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; @Injectable() export class AppService { constructor(private readonly configService: ConfigService) {} getDatabaseHost(): string { return this.configService.[1]('DATABASE_HOST'); } }
The get method of ConfigService retrieves the value of a configuration key.
Fix the error in the code to load environment variables from a custom path.
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ envFilePath: [1], }), ], }) export class AppModule {}
The envFilePath option expects a string path with quotes, like '.env.production'.
Fill both blanks to create a configuration object with a default value and type safety.
import { registerAs } from '@nestjs/config'; export default registerAs('database', () => ({ host: process.env.DB_HOST || [1], port: Number(process.env.DB_PORT) || [2], }));
Default host is usually 'localhost' and default port for PostgreSQL is 5432.
Fill all three blanks to create a typed configuration interface and use it in a service.
import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; interface AppConfig { apiKey: string; timeout: number; } @Injectable() export class ApiService { constructor(private configService: ConfigService) {} getApiKey(): string { return this.configService.[1]<[2]>('API_KEY'); } getTimeout(): number { return this.configService.get<[3]>('TIMEOUT'); } }
The get method is used with a generic type to ensure type safety. AppConfig is the interface type, and number is the type for timeout.