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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mich4l/nestjs-redis

v1.1.0

Published

Redis Nest.js connector module

Downloads

70

Readme

Redis module for Nest.js

Redis module based on popular npm library ioredis.

Features:

  • Simple codebase
  • Graceful shutdown
  • Multiple connections
  • Cluster module
  • Simple lifecycle hooks (onReady, beforeShutdown)

Installation

# pnpm:
pnpm add @mich4l/nestjs-redis ioredis
# npm:
npm install --save @mich4l/nestjs-redis ioredis
# yarn:
yarn add @mich4l/nestjs-redis ioredis

Usage

Standard configuration

import { Module } from '@nestjs/common';
import { RedisModule } from '@mich4l/nestjs-redis';

@Module({
  imports: [
    RedisModule.forRoot({
      host: 'localhost',
      port: 6379,        
    })
  ]
})
export class AppModule {}

Async configuration with useFactory

import { Module } from '@nestjs/common';
import { RedisModule } from '@mich4l/nestjs-redis';

@Module({
  imports: [
    RedisModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        connectUrl: config.get<string>('REDIS_URL')
      })
    })
  ]
})
export class AppModule {}

Async configuration with useClass

import { Module } from '@nestjs/common';
import { 
  RedisOptionsFactory, 
  IORedisOptions, 
  RedisModule, 
} from '@mich4l/nestjs-redis';

@Injectable()
export class ConfigService implements RedisOptionsFactory {
  createRedisOptions(): IORedisOptions {
    return {
      connectUrl: 'redis://localhost:6379',
    };
  }
}

@Module({
  imports: [
    RedisModule.forRootAsync({
      useClass: ConfigService,
    })
  ]
})
export class AppModule {}

Async configuration with useExisting

@Module({
  imports: [
    RedisModule.forRootAsync({
      imports: [ConfigModule],
      useExisting: ConfigService,
    })
  ]
})
export class AppModule {}

Example

Redis configuration

app.module.ts

@Module({
  imports: [
    RedisModule.forRoot({
      name: 'conn1',
      host: 'localhost',
      port: 6379,
    }),
    ExampleModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Injecting Redis client to service

example.service.ts

import { Inject, Injectable } from '@nestjs/common';
import { InjectRedis } from '@mich4l/nestjs-redis';
import { Redis } from 'ioredis';

@Injectable()
export class ExampleService {
    constructor(
        @InjectRedis('conn1')
        private readonly redis: Redis,
    ) {}

    async getAllPosts() {
        const key = 'posts';
        const result = await this.redis.get(key);

        return JSON.parse(result);
    }
}

Multiple connections

Note: Every connection requires unique name!

@Module({
  imports: [
    RedisModule.forRoot({
      name: 'conn1',
      host: 'localhost',
      port: 6379,
    }),
    RedisModule.forRoot({
      name: 'conn2',
      host: 'localhost',
      port: 2137,
    })
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Async named connections

Example with Nest.js config module:

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: ConfigSchema,
    }),
    RedisModule.forRootAsync({
      name: 'my-redis',
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => ({
        host: config.get('REDIS_HOST'),
        port: config.get('REDIS_PORT'),
      }),
    }),
  ]
})
export class AppModule {}

Inject Redis client via token

Example with Nest.js Throttler and Redis storage

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: ConfigSchema,
    }),
    RedisModule.forRootAsync({
      name: 'my-redis',
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => ({
        host: config.get('REDIS_HOST'),
        port: config.get('REDIS_PORT'),
      }),
    }),
    ThrottlerModule.forRootAsync({
      inject: [injectRedisToken('my-redis')],
      useFactory: (redis: Redis) => ({
        storage: new ThrottlerStorageRedisService(redis),
      })
    })
  ]
})
export class AppModule {}

RedisModule is global by default

Set option isGlobal to false to change it.

@Module({
  imports: [
    RedisModule.forRoot({
      isGlobal: false,
      host: 'localhost',
      port: 6379,        
    })
  ]
})
export class AppModule {}

Lifecycle hooks

You can use lifecycle hooks to handle errors.

@Module({
  imports: [
    RedisModule.forRoot({
      name: 'conn1',
      host: 'localhost',
      port: 6379,
      onReady: (client: Redis) => {
        client.on('error', handleError);
      },
      beforeShutdown: async (client: Redis) => {
        await client.flushall();
      }
    }),
  ],
})
export class AppModule {}