iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🥺
I built a library to simplify NestJS DI
@nestjs-modular/inject
Every time Repositories or UseCases increase, manually performing DI every time is tedious, so I created a library that allows you to perform DI for an entire directory.
Click here for usage examples:
Writing DI manually every time is tedious
import { Module } from '@nestjs/common';
@Module({
providers: [
UserCreateUseCase,
UserDeleteUseCase,
],
exports: [
UserCreateUseCase,
UserDeleteUseCase,
],
controllers: [
TasksController,
],
})
export class UsersModule {}
Don't you find yourself writing code like this as your endpoints increase?
Forgetting to perform DI when a new UseCase is added, leading to build errors...
Let's perform DI for everything by specifying a directory
import { Module } from '@nestjs/common';
import { InjectConditions, InjectModule } from '@nestjs-modular/inject';
import path from 'path';
const useCases: InjectConditions = {
path: path.resolve(__dirname, './usecases'),
includeFileNames: [/\\.usecase$/],
includeExportNames: [/UseCase$/],
};
@Module({
imports: [
InjectModule.forRootAsync({
providers: useCases,
exports: useCases,
}),
],
controllers: [
TasksController,
],
})
export class UsersModule {}
With @nestjs-modular/inject, you can perform DI for an entire directory.
Even if the number of UseCases increases, they will be injected automatically, eliminating build errors caused by simple mistakes.
How it works
Internally, the mechanism works by recursively searching directories and performing dynamic import.
(It might be too heavy to use if there are too many files in the specified directory...)
Discussion