Implement scalable, enterprise-grade architecture patterns and NestJS internals.
Welcome to Custom Providers & Dynamic Modules in NestJS! This chapter will guide you through advanced patterns for creating reusable and configurable modules using factory-based approaches. You'll learn how to leverage providers like useClass
, useFactory
, and useValue
with custom tokens.
In NestJS, providers are used to bind services to the container. Custom providers allow you to create more flexible and reusable modules by using factory functions or values.
import { Injectable } from '@nestjs/common';
@Injectable()
export class LoggerService {
log(message: string) {
console.log(`Logger: ${message}`);
}
}
export const loggerProvider = {
provide: 'LOGGER',
useClass: LoggerService,
};
export const cacheProvider = {
provide: 'CACHE_CONFIG',
useFactory: (config) => ({
ttl: config.TTL,
maxItems: config.MAX_ITEMS,
}),
inject: ['APP_CONFIG'],
};
Dynamic modules allow you to create reusable and configurable modules that can be loaded at runtime. They use factory-based approaches to generate providers based on input configurations.
import { Module } from '@nestjs/common';
export class CacheModule {
static forRoot(config) {
return {
module: CacheModule,
providers: [
{
provide: 'CACHE_CONFIG',
useValue: config,
},
],
};
}
}
In this chapter, we'll explore interceptors, middleware, and hooks in NestJS. These powerful tools help you manage request/response lifecycle and keep your application clean and maintainable.
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Request received');
const start = Date.now();
return next.handle().pipe(
tap(() => {
console.log(`Response sent in ${Date.now() - start}ms`);
})
);
}
}
Middleware functions are used to perform tasks that are common across your application such as request logging, authentication, and error handling.
Hooks allow you to execute code at specific points in the application lifecycle. Nest provides hooks for modules, controllers, and services.
Question 1 of 10