npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nestjs-moduly

v1.4.0

Published

Simplify NestJS module management with organized groups, singleton instance sharing, and dual injection support

Readme

NestJS Moduly

NPM Version License Downloads TypeScript Zero Dependencies

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-moduly
yarn add nestjs-moduly
pnpm add nestjs-moduly

Quick 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.ts into domain files (database.ts, cache.ts, repositories.ts, ...) and join them with a barrel. See examples/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 a useValue provider, which is always a singleton — its scope is 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 request

Or override a single instance with .scope():

Repository.Users = () => new UserRepository(Database.Primary);
Repository.Users.scope(Scope.TRANSIENT); // only Users is transient

Scoped 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.

  1. Fork repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT © Victor Bueno


Built with NestJS