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

Published

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

Downloads

30

Readme

NestJS Moduly

NPM Version License Downloads TypeScript NestJS

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 {}

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 | Sets the injection scope | | tokenPrefix | string | group name | Custom prefix for injection tokens |

.scope(scope)

Sets the injection scope for an instance.

Repository.Users = new UserRepository(config);
Repository.Users.scope(Scope.REQUEST); // New instance per HTTP request

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 Instance Declaration

Declare all instances in a single instances.ts file:

// instances.ts
export const Database = createInstanceGroup('Database');
export const Repository = createInstanceGroup('Repository');

Database.Primary = new DatabaseService(config);
Repository.Users = new UserRepository(Database.Primary);

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
// 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