Sling Academy
Home/Node.js/How to Use Global NestJS Modules in Decorator

How to Use Global NestJS Modules in Decorator

Last updated: December 31, 2023

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.

Next Article: NestJS & Mongoose Validation Error: Comprehensive Fix Guide

Previous Article: Fixing NestJS Error: Cannot Find Module When Running Tests

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates