Menu
CoddyTech

A Second Module

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

The new StatsController lives in its own module but needs TasksService, which belongs to TasksModule. A module's providers are private to it until it shares them.

@Module({
    providers: [UsersService],
    exports: [UsersService],
})
export class UsersModule {}

@Module({
    imports: [UsersModule],
    controllers: [ProfileController],
})
export class ProfileModule {}

exports makes a provider available to other modules, and imports brings in a module's exports. ProfileController can now ask for UsersService and gets the same instance as UsersModule. Listing UsersService in ProfileModule's own providers would start too, but builds a second instance with its own data.

A module's routes only exist once AppModule imports it.

challenge icon

Challenge

Easy

A new page of the board shows counts: how many tasks exist, how many are done and how many are open. The starter adds StatsController for it, in its own module, StatsModule. The controller is already written. It only needs the same TasksService that TasksController uses, so both see the same tasks. Three files change, one line each.

  1. In src/tasks/tasks.module.ts, share the service: add exports to the module, listing TasksService. A module's providers stay private to it until it exports them.
  2. In src/stats/stats.module.ts, add imports, listing TasksModule. Now StatsController can ask for TasksService and gets the same instance. Do not list TasksService in StatsModule's own providers. That would build a second service with its own copy of the tasks, and here the app would not even start, because TasksService needs ClockService.
  3. In src/app.module.ts, add StatsModule to imports, next to TasksModule. Nest only creates routes for the modules that AppModule imports.

Try it: send GET /stats. You get 200 and:

{ "total": 3, "done": 1, "open": 2 }

POST { "title": "Buy milk" } to /tasks, then send GET /stats again:

{ "total": 4, "done": 1, "open": 3 }

If the numbers did not change, StatsController got a different service than TasksController.

Try it yourself

import { Module } from '@nestjs/common';
import { StatsController } from './stats.controller';

// StatsController needs TasksService, which belongs to TasksModule.
@Module({
    controllers: [StatsController],
})
export class StatsModule {}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in TypeScript and NestJS

Practice on your own: Express playground