nestjs-moduly
v1.4.0
Published
Simplify NestJS module management with organized groups, singleton instance sharing, and dual injection support
Maintainers
Readme
NestJS Moduly
Simplify NestJS module management. Declare dependencies once, share singleton instances across modules, and inject with or without @Inject().
Requirements
- NestJS 11.x or higher
- Node.js 16+
Installation
npm install nestjs-modulyyarn add nestjs-modulypnpm add nestjs-modulyQuick Start
1. Declare Dependencies
Create a file to declare all your instances once:
// instances.ts
import { createInstanceGroup } from 'nestjs-moduly';
import { UserRepository } from './user.repository';
import { DatabaseService } from './database.service';
const database = new DatabaseService({ host: 'localhost', port: 5432 });
export const Repository = createInstanceGroup('Repository');
Repository.Users = new UserRepository(database);2. Import in Modules
Use the declared instances in the imports array of your modules:
// app.module.ts
import { Module } from '@nestjs/common';
import { Repository } from './instances';
@Module({
imports: [
Repository.Users,
],
controllers: [UserController],
})
export class AppModule {}3. Inject Dependencies
Inject using the concrete class type:
@Controller('users')
export class UserController {
constructor(private readonly userRepository: UserRepository) {}
@Get()
findAll() {
return this.userRepository.findAll();
}
}How It Works
Instance Groups
Instance groups organize your dependencies into logical categories (Repository, Database, Infrastructure, etc.):
export const Repository = createInstanceGroup('Repository');
export const Database = createInstanceGroup('Database');
export const Storage = createInstanceGroup('Storage');
Repository.Users = new UserRepository(database);
Repository.Products = new ProductRepository(database);
Database.Primary = new DatabaseService(config);
Storage.S3 = new S3Service(s3Config);Automatic Module Wrapping
Each instance automatically becomes a NestJS dynamic module. Use them in the imports array:
@Module({
imports: [
Repository.Users,
Database.Primary,
Storage.S3,
],
})
export class AppModule {}Singleton Sharing
Instances are shared across your entire application. Declare once, use anywhere:
// app.module.ts
@Module({
imports: [Database.Primary],
})
export class AppModule {}
// product.module.ts
@Module({
imports: [Database.Primary], // Same singleton instance
})
export class ProductModule {}Lazy Declaration (Recipes)
By default an instance is built eagerly, the moment you assign it. That forces you to declare dependencies before their consumers and to keep every declaration in the right order by hand:
// Eager: DatabaseService is created here and MUST come before UserRepository
const database = new DatabaseService(config);
Repository.Users = new UserRepository(database);Assign a function instead, and it becomes a lazy recipe. moduly runs it on demand and resolves any instance you reference inside it:
Repository.Users = () => new UserRepository(Database.Primary, Cache.Redis);
Database.Primary = () => new DatabaseService(config);
Cache.Redis = () => new CacheService();The rule is simple — assign a function → lazy recipe; assign anything else (an instance, a config object, a primitive) → eager value, exactly as before. Lazy is fully opt-in and nothing breaks.
Why it matters (especially in large projects):
- Order-independent. Recipes run at bootstrap in dependency order, so it no longer matters which line — or which file — declares an instance first.
- Split wiring across files. Because order is irrelevant, you can break a
large
instances.tsinto domain files (database.ts,cache.ts,repositories.ts, ...) and join them with a barrel. Seeexamples/03-advanced. - Only builds what you use. An instance whose module is never imported and is referenced by no recipe is never created.
- Singletons + cycle detection. Each recipe runs at most once (shared singleton), and a circular dependency throws a clear error instead of overflowing the stack.
Inside a recipe, reference other instances directly through their groups
(Database.Primary) and moduly resolves them to the real instance. Outside a
recipe (e.g. imports: [Database.Primary]) the same property is the module
wrapper, as usual.
Dual Injection
Natural Injection (recommended):
constructor(
private userRepository: UserRepository, // No @Inject() needed
) {}Flexible Injection (with @Inject()):
constructor(
@Inject('Database.Primary') private primaryDb: DatabaseService,
@Inject('Database.Replica') private replicaDb: DatabaseService,
) {}API Reference
createInstanceGroup(name, options?)
Creates a new instance group.
const Repository = createInstanceGroup('Repository', {
useClassAsToken: true, // Enable dual injection (default: true)
global: false, // Make available globally (default: false)
scope: Scope.DEFAULT, // Injection scope (default: Scope.DEFAULT)
});Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| useClassAsToken | boolean | true | Enables injection using the class constructor |
| global | boolean | false | Makes instances available without importing |
| scope | Scope | Scope.DEFAULT | Injection scope (applies to lazy recipes only) |
| tokenPrefix | string | group name | Custom prefix for injection tokens |
Scopes (REQUEST / TRANSIENT)
Scopes only take effect on lazy recipes (the
() => new X()form). An eager value is auseValueprovider, which is always a singleton — itsscopeis ignored. Use a recipe when you need REQUEST or TRANSIENT.
Set the scope once for a whole group:
const Request = createInstanceGroup('Request', { scope: Scope.REQUEST });
Request.Context = () => new RequestContextService(); // new instance per requestOr override a single instance with .scope():
Repository.Users = () => new UserRepository(Database.Primary);
Repository.Users.scope(Scope.TRANSIENT); // only Users is transientScoped instances are registered under their string token only (the class isn't known before the first build), so inject them with the token:
constructor(@Inject('Request.Context') private ctx: RequestContextService) {}
// or: moduleRef.resolve('Request.Context')A scoped instance is truly per-request/per-injection only when NestJS injects it directly. If you embed it inside another singleton recipe, that recipe captures a single instance — so keep scoped instances as leaf providers.
Helpers
- getInjectionToken(group, key): Get token for an instance
- getAllInstances(): Get all registered instances as a Map
- instanceGroupToArray(group): Convert a group to array of providers
- allInstanceGroupsToArray(): Convert all groups to array of providers
Best Practices
1. Centralize or Split Instance Declaration
For small projects, declare everything in a single instances.ts. For large
projects, split declarations into domain files and join them with a barrel —
lazy recipes make this safe because load order stops mattering:
// instances/database.ts
export const Database = createInstanceGroup('Database');
Database.Primary = () => new DatabaseService(config);
// instances/repositories.ts
import { Database } from './database';
export const Repository = createInstanceGroup('Repository');
Repository.Users = () => new UserRepository(Database.Primary);
// instances/index.ts
export * from './database';
export * from './repositories';See examples/03-advanced for the full domain-split pattern.
2. Use Imports, Not Providers
Always use imports to register instances:
// Correct
@Module({
imports: [Repository.Users, Database.Primary],
})
// Incorrect (will cause errors)
@Module({
providers: [Repository.Users, Database.Primary],
})3. Inject Using Concrete Classes
Use the concrete class type for injection, not interfaces:
// Correct
constructor(private readonly userRepository: UserRepository) {}
// Incorrect (TypeScript interfaces don't exist at runtime)
constructor(private readonly userRepository: IUserRepository) {}4. Use Scopes Appropriately
- DEFAULT (Singleton): Database, Cache, Stateless services
- REQUEST: Request-specific data, user context
- TRANSIENT: Stateful services needing fresh instances
Scopes require the lazy recipe form (() => new X()):
// Request-scoped service
export const RequestContext = createInstanceGroup('RequestContext', {
scope: Scope.REQUEST,
});
RequestContext.Context = () => new RequestContextService();Examples
See the examples/ directory for complete working examples:
- 01-basic: Simple repository setup
- 02-intermediate: Multiple services, databases, and caching
- 03-advanced: Global modules, scopes, and complex dependency chains
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT © Victor Bueno
Built with NestJS
