Menu
CoddyTech

Configuration Values

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 12 of 24.

GET /tasks is about to return its tasks one page at a time, as in section 3. How many tasks fit on a page is a setting, so it should come from the environment instead of being typed into the code. 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

This step opens the course’s prepared Nest task tracker project, rather than your project files from A Second Module (including src/stats/stats.module.ts). Your earlier work stays in its own lesson. Read the supplied files before editing src/tasks/tasks.module.ts. This copy contains the Nest service and stats module, with pagination code supplied.

This prepared task tracker adds pagination to GET /tasks. In src/tasks/tasks.module.ts, register a value provider named PAGE_SIZE. Read the environment value, default to 10 when absent, and convert it to a number.

In src/tasks/tasks.controller.ts, remove the fixed pageSize field. Receive the provider in the constructor as a private readonly numeric field named pageSize. Use @Inject with the exact token name; the import and pagination code are supplied.

Try it: Run supplies PAGE_SIZE=2. GET /tasks returns two items, page 1, total 3 and pages 2. GET /tasks?page=2 returns the remaining task. Without that environment variable, the default is ten items per page.

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

Practice on your own: Express playground