Menu
CoddyTech

Configuration Values

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 9 of 17.

The page size is a setting, so it should come from the environment instead of being typed into the controller. A value provider registers any value under a name, called a token.

providers: [
    { provide: 'CURRENCY', useValue: process.env.CURRENCY ?? 'EUR' },
],

constructor(@Inject('CURRENCY') private readonly currency: string) {}

A string has no class for Nest to read from the parameter's type, so @Inject('CURRENCY') names the token. It must be spelled the same in both places: a typo stops the app with the "can't resolve dependencies" error. Environment values are always strings; convert them with Number() when you need a number.

challenge icon

Challenge

Easy
  • Register PAGE_SIZE in TasksModule: process.env.PAGE_SIZE as a number, 10 when unset. This lesson sets it to 2.
  • GET /tasks answers { items, page, total, pages }; ?page=2 gives the next page, and done still filters.
  • Send GET /tasks, GET /tasks?page=2, then GET /tasks?page=9.

Try it yourself

import { Module } from '@nestjs/common';
import { ClockService } from './clock.service';
import { TasksController } from './tasks.controller';
import { TasksService } from './tasks.service';

@Module({
    controllers: [TasksController],
    providers: [TasksService, ClockService],
    exports: [TasksService],
})
export class TasksModule {}

All lessons in TypeScript and NestJS