typescript 48 lines · 8 steps

Building a dynamic Redis module in NestJS

A configurable NestJS module that provides a shared Redis client through both static and async factory registration.

Explained by highlit
1import { DynamicModule, Module, Provider } from '@nestjs/common';
2import Redis, { RedisOptions } from 'ioredis';
3 
4export const REDIS_CLIENT = Symbol('REDIS_CLIENT');
5export const REDIS_OPTIONS = Symbol('REDIS_OPTIONS');
6 
7export interface RedisModuleAsyncOptions {
8 useFactory: (...args: any[]) => Promise<RedisOptions> | RedisOptions;
9 inject?: any[];
10}
11 
12@Module({})
13export class RedisModule {
14 static forRoot(options: RedisOptions): DynamicModule {
15 const clientProvider: Provider = {
16 provide: REDIS_CLIENT,
17 useValue: new Redis(options),
18 };
19 
20 return {
21 module: RedisModule,
22 global: true,
23 providers: [clientProvider],
24 exports: [clientProvider],
25 };
26 }
27 
28 static forRootAsync(options: RedisModuleAsyncOptions): DynamicModule {
29 const optionsProvider: Provider = {
30 provide: REDIS_OPTIONS,
31 useFactory: options.useFactory,
32 inject: options.inject ?? [],
33 };
34 
35 const clientProvider: Provider = {
36 provide: REDIS_CLIENT,
37 useFactory: (opts: RedisOptions) => new Redis(opts),
38 inject: [REDIS_OPTIONS],
39 };
40 
41 return {
42 module: RedisModule,
43 global: true,
44 providers: [optionsProvider, clientProvider],
45 exports: [clientProvider],
46 };
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A DynamicModule lets a module return its own provider configuration at runtime instead of declaring it statically.
  2. 2Symbol tokens give injectable providers stable, collision-proof identifiers when there's no class to inject.
  3. 3Offering both forRoot and forRootAsync lets callers pass config directly or resolve it lazily via a factory and injected dependencies.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a dynamic Redis module in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code