How to Use Global NestJS Modules in Decorator

Updated: December 31, 2023 By: Guest Contributor Post a comment

Introduction

Working with modern application frameworks often requires a deep understanding of modularization. In NestJS, decorators are used to define modular configuration, granting reusability and order. This tutorial comprehensively guides you on leveraging global modules in decorators, enhancing your NestJS application’s structure and maintainability.

Understanding Global Modules

Before diving into the application of global modules, it’s essential to comprehend what exactly a global module in NestJS is. In NestJS, a module encapsulates providers, controllers, and imports and exports them as a single cohesive unit. When you declare a module as ‘global’ using the @Global() decorator, you make its exports available across your entire application, without needing to import them explicitly in other modules.

import { Module, Global } from '@nestjs/common';

@Global()
@Module({
  providers: [...],
  exports: [...]
})
export class SharedModule {}

Using the SharedModule in a Decorator

To apply the SharedModule to a decorator in NestJS, you’ll need to follow the right convention. Consider a typical decorator implementation without global modules:

import { Injectable } from '@nestjs/common';

@Injectable()
export class CustomDecorator {
  // Decorator functionality ...
}

Let’s elevate this example by applying SharedModule’s capabilities globally:

import { Injectable, Inject } from '@nestjs/common';

@Injectable()
export class CustomDecorator {
  constructor(@Inject(SharedService) private sharedService: SharedService) {}

  customMethod() {
    // Use 'sharedService' functionality here
  }
}

In this case, SharedService is an exported provider from SharedModule and it’s now available application-wide thanks to our global module configuration.

Advanced Global Module Patterns

Now let’s tackle a more advanced scenario where our global module is not just sharing common functionality, but it’s also meant to streamline complex configurations.

// shared.constants.ts
export const CONFIG_OPTIONS = 'CONFIG_OPTIONS';

// shared.module.ts
... // Specified earlier with @Global() decorator

// config.options.ts
import { CONFIG_OPTIONS } from './shared.constants';

export function createConfigOptions(options) {
  return {
    provide: CONFIG_OPTIONS,
    useFactory: () => options,
  };
}

// In the app module or core module
import { Module } from '@nestjs/common';
import { SharedModule, createConfigOptions } from './shared.module';

Module({
  imports: [SharedModule.forRoot(createConfigOptions({ /* options here */ }))],
  // Other definitions
})
export class AppModule { }

In this pattern, we’re not only using global modules but providing a dyanmic method to customize the configuration through a factory function, keeping in line with the fundamentals of Dependency Injection principles in NestJS.

Practical Use-Cases of Global Modules

Global modules shine in scenarios where you have common functionality like authentication, logging, or configuration that needs to be accessible in several parts of your application. Here are some practical examples to demonstrate how you can use global modules:

Shared Logging Module

@Global()
@Module({
  providers: [LoggerService],
  exports: [LoggerService]
})
export class LoggerModule {}

// Usage in any module without explicit import
@Injectable()
export class AnyService {
  constructor(private logger: LoggerService) {}
}

Common Configuration Module

@Global()
@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: TransformInterceptor
    }
  ],
  exports: [APP_INTERCEPTOR]
})
export class CoreModule {}

// Auto-applied interceptor in any module
@Controller()
export class AnyController { /* ... */ }

Conclusion

Global modules in NestJS are powerful tools for developers seeking to maintain abstraction while promoting the reuse of common functionalities across applications. With the guided examples, you’re now more equipped to implement global modules effectively, which in turn can lead to a more structured and manageable codebase. Embrace global modules where it makes sense, and always remember to balance compactness with clarity.