0
0
NestJSframework~10 mins

Environment variables in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to load environment variables in a NestJS service.

NestJS
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AppService {
  constructor(private readonly [1]: ConfigService) {}

  getDatabaseHost(): string {
    return this.configService.get<string>('DATABASE_HOST');
  }
}
Drag options to blanks, or click blank then click option'
AconfigSrv
BConfigService
Cconfig
DconfigService
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class name instead of the instance name in the constructor.
Using a name that does not match the injected service.
2fill in blank
medium

Complete the code to access an environment variable named 'PORT' as a number.

NestJS
const port = this.configService.get<number>([1]);
Drag options to blanks, or click blank then click option'
A'port'
B'PORT'
C'Port'
D'server_port'
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase or mixed case keys that do not match the environment variable.
Using a wrong variable name.
3fill in blank
hard

Fix the error in the code to correctly load environment variables in the main app module.

NestJS
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule.[1]()],
})
export class AppModule {}
Drag options to blanks, or click blank then click option'
Aload
Bregister
CforRoot
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent method like 'load' or 'init'.
Forgetting to call the method as a function.
4fill in blank
hard

Fill both blanks to create a configuration object that reads 'API_KEY' and 'API_SECRET' from environment variables.

NestJS
export default () => ({
  apiKey: process.env.[1],
  apiSecret: process.env.[2],
});
Drag options to blanks, or click blank then click option'
AAPI_KEY
Bapi_key
CAPI_SECRET
Dapi_secret
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase or camelCase keys that do not match environment variables.
Mixing up the keys for apiKey and apiSecret.
5fill in blank
hard

Fill all three blanks to create a NestJS service method that returns the port number from environment variables with a default fallback.

NestJS
getPort(): number {
  return this.configService.get<number>([1], [2]) ?? [3];
}
Drag options to blanks, or click blank then click option'
A'PORT'
Bundefined
C3000
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Passing wrong keys or default values.
Not providing a fallback value.