Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Modules

A module is a class with the @Module() decorator that groups the code of one part of the application: controllers, services and settings. The blog will have modules for posts, comments and users, and the root AppModule brings them together.

The posts module

Create a module with the CLI:

nest g module posts

The file src/posts/posts.module.ts appears:

// src/posts/posts.module.ts
import { Module } from '@nestjs/common';
 
@Module({})
export class PostsModule {}

The module is empty for now. The CLI has already connected it to the root module — src/app.module.ts now has imports: [PostsModule].

The four module properties

PropertyWhat goes in it
controllersControllers that handle this module's requests
providersServices and other classes that NestJS creates itself
importsOther modules whose services this one uses
exportsIts own services that other modules may use

Once the module has a controller and a service, it looks like this:

// src/posts/posts.module.ts
import { Module } from '@nestjs/common';
import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';
 
@Module({
  controllers: [PostsController],
  providers: [PostsService],
})
export class PostsModule {}

A service for another module

By default a service is visible only inside its own module. Comments need to check that a post exists, so the posts module exports its service:

// src/posts/posts.module.ts
@Module({
  controllers: [PostsController],
  providers: [PostsService],
  exports: [PostsService],
})
export class PostsModule {}

And the comments module imports the posts module:

// src/comments/comments.module.ts
import { Module } from '@nestjs/common';
import { PostsModule } from '../posts/posts.module';
import { CommentsService } from './comments.service';
 
@Module({
  imports: [PostsModule],
  providers: [CommentsService],
})
export class CommentsModule {}

Now CommentsService can receive PostsService — the lesson about services shows how.

The root module

// src/app.module.ts
import { Module } from '@nestjs/common';
import { PostsModule } from './posts/posts.module';
import { CommentsModule } from './comments/comments.module';
 
@Module({
  imports: [PostsModule, CommentsModule],
})
export class AppModule {}

At startup NestJS begins with AppModule and walks through all imports. The terminal shows lines like PostsModule dependencies initialized — the module was found and built.

Common mistake

A module exports a service, but the other module forgets to import it. At startup NestJS prints Nest can't resolve dependencies of the CommentsService (?) and names the module it searched. Both steps are needed: exports in the owning module and imports in the module that uses the service. Do not add someone else's service to your own providers — that creates a second, independent copy.

Thanks for reading!

Donate to the site — we work hard for you.