Create or Import Module
You can either create a module by creating a folder and adding your classes following the NestJS conventions, or you can import a compatible module directly into the src/modules/ folder.
Prerequisites
There are a few prerequisites for your module to be recognized:
The
@DynamicModule({})decorator must be added to the module.The
.tsfile must end with.module.ts.
Example Usage
When you move this module into a designated folder like src/modules, it can be automatically loaded by your dynamic loading service. The controller exposes two endpoints to test the API:
This module example can serve as a foundation in the documentation to explain how to create a simple module in NestJS while adhering to SOLID principles and the modular architecture of your API.
Component Explanation
MyCustomModule: The main module that encapsulates the controller and the service.
import { Module } from '@nestjs/common';
import { MyCustomService } from './services/my-custom.service';
import { MyCustomController } from './controllers/my-custom.controller';
import { DynamicModule } from '../../common/decorators/dynamic.module.decorator';
@DynamicModule({})
@Module({
controllers: [MyCustomController],
providers: [MyCustomService],
})
export class MyCustomModule {}MyCustomController: Responsible for handling incoming HTTP requests. It provides two routes:
GET /mycustomto retrieve all entries.POST /mycustomto create a new entry.
MyCustomService: Handles the business logic related to "MyCustom" entities, storing data in memory and allowing creation and retrieval operations.
CreateMyCustomDto: A Data Transfer Object (DTO) used to validate incoming data when creating a new "MyCustom" entry.
MyCustomServiceInterface: Defines the contracts the service must adhere to, ensuring compliance with best practices.
MyCustomModule Decorator: A custom decorator that can be used to add metadata to dynamic modules (optional but useful for automation or dynamic loading scenarios).
MyCustomSubModule: A submodule loader is also available. It searches within your module path, for example src/modules/mycustommodule/, to see if a subModules folder exists. It scans this folder looking for the following prerequisites:
The submodule decorator must be added: @MYCUSTOMDECORATOR({}).
The custom decorator is defined within a service who extends BaseSubModulesLoader:
The submodule file must end with
.module.ts.
The submodule functions as a fully independent module and can implement the same tools as a parent module. However, its loading depends on the parent module.
Last updated