Complete the code to load environment variables in a NestJS service.
import { ConfigService } from '@nestjs/config'; @Injectable() export class AppService { constructor(private readonly [1]: ConfigService) {} getDatabaseHost(): string { return this.configService.get<string>('DATABASE_HOST'); } }
The constructor parameter should be named configService to use the injected ConfigService instance.
Complete the code to access an environment variable named 'PORT' as a number.
const port = this.configService.get<number>([1]);Environment variables are case-sensitive and usually uppercase. The correct key is 'PORT'.
Fix the error in the code to correctly load environment variables in the main app module.
import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ConfigModule.[1]()], }) export class AppModule {}
The ConfigModule must be imported with forRoot() to load environment variables globally.
Fill both blanks to create a configuration object that reads 'API_KEY' and 'API_SECRET' from environment variables.
export default () => ({
apiKey: process.env.[1],
apiSecret: process.env.[2],
});Environment variables are usually uppercase and underscore separated. Use API_KEY and API_SECRET.
Fill all three blanks to create a NestJS service method that returns the port number from environment variables with a default fallback.
getPort(): number {
return this.configService.get<number>([1], [2]) ?? [3];
}The method gets the 'PORT' variable, passes undefined as default value to get, and uses 3000 as fallback if undefined.