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
Easy- Register
PAGE_SIZEinTasksModule:process.env.PAGE_SIZEas a number, 10 when unset. This lesson sets it to 2. GET /tasksanswers{ items, page, total, pages };?page=2gives the next page, anddonestill filters.- Send
GET /tasks,GET /tasks?page=2, thenGET /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 {}