Modules

Module is a class with @Module({}) decorator. This decorator provides metadata, which framework uses to organize application structure.

Right now, it is our ApplicationModule:

import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
    controllers: [ UsersController ],
    components: [ UsersService ],
})
export class ApplicationModule {}

By default, modules encapsulate each dependency. It means, that it is not possible to use its components / controllers outside module.

Each module can also import another modules. In fact, you should think about Nest Modules as a tree of modules.

Let's move UsersController and UsersService to UsersModule. Simply create new file e.g. users.module.ts with below content:

import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
    controllers: [ UsersController ],
    components: [ UsersService ],
})
export class UsersModule {}

Then import UsersModule into ApplicationModule (our main application module):

import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';

@Module({
    modules: [ UsersModule ]
})
export class ApplicationModule {}

It's everything.

As might be seen, with Nest you can naturally split your code into separated and reusable modules!

Shared instance

You already know that Module encapsulates its components. What if you want to share instance between two or more modules? With Nest - it is pretty easy. You only have to use@Shared() decorator and add exports array, just like that:

import { Module, Shared } from '@nestjs/common';

@Shared()
@Module({
    controllers: [ UsersController ],
    components: [ UsersService ],
    exports: [ UsersService ],
})
export class UsersModule {}

That's all. It is especially powerful feature. You can read more about it in Advanced / SharedModule section.

Dependency Injection

Module can easily inject components, which belongs to itself:

@Module({
    controllers: [ UsersController ],
    components: [ UsersService, ChatGateway ],
})
export class UsersModule implements NestModule {
    constructor(private usersService: UsersService) {}
}

Furthermore, components also can inject modules:

export class UsersController {
    constructor(private module: UsersModule) {}
}

results matching ""

    No results matching ""