@betsys-nestjs/redis
TypeScript icon, indicating that this package has built-in type declarations

5.1.0 • Public • Published

Redis library

This NestJS library is used for Redis communication. It supports both single Redis server and Redis Cluster. In the background it uses ioredis. It also provides abstractions for custom logging and monitoring based on user's implementation and is optional.

Dependencies

Package Version
ioredis ^5.2.4
@nestjs/terminus ^10.0.0
@nestjs/common ^10.0.0
@nestjs/core ^10.0.0
reflect-metadata ^0.1.13
rxjs ^7.8.0

Usage

Setup of library

  • To start using this library simply import RedisModule to your module.
@Module({
    imports: [
        RedisModule.forFeature(redisConfig),
    ]
})
export class AppModule {
    // ...
}
  • Pass these arguments to forFeature:
  • redisConfig - must be either RedisSingleNodeConnectionConfig for single redis node or RedisClusterConnectionConfig for node cluster
const redisSingleNodeConfig: RedisSingleNodeConnectionConfig = {
    uri: 'redis://redis:7000',
    // unique app prefix for all keys
    prefix: 'app_prefix',
    // redis options from https://luin.github.io/ioredis/index.html#RedisOptions
    redisOptions: {
        // timeout in ms
        commandTimeout: 1000,
    },
    // key to determine instance of used redis module
    dbHandle: 'DB1',
    // this service must implement provided interface (optional param)
    // implements `RedisLoggerInterface` described below
    logger: YourLoggerService,
    // these services must implement both of the provided abstractions below (optional param)
    monitoring: {
        // implements `RedisTimeMonitoringInterface` described below
        time: YourTimeMonitoringService,
        // implements `RedisConnectionMonitoringInterface` described below
        connection: YourConnectionMonitoringService
    }

}

const redisClusterConfig: RedisClusterConnectionConfig = {
    clusterURIs: [
        'redis://redis:7001',
        'redis://redis:7002'
    ],
    prefix: 'app_prefix_different',
    redisOptions: {
        commandTimeout: 3000,
    },
    dbHandle: 'DB1',
    logger: YourLoggerService,
    monitoring: {
        time: YourTimeMonitoringService,
        connection: YourConnectionMonitoringService
    }
}
  • Interface for optional logger service:
interface RedisLoggerInterface {
    // setup anything before logging starts like any prefix etc
    setContext(context: string): void;

    // method used to internally logs open/closed connections
    debug(message: string): void;
}
  • Interfaces for optional monitoring services

  • Connection monitoring service:

interface RedisConnectionMonitoringInterface {
    // Executes any monitoring operation based on your implementation whenever there's new connection
    connectionOpened(handle: string): void;

    // Executes any monitoring operation based on your implementation whenever there's closed connection
    connectionClosed(handle: string): void;
}
  • Time monitoring service:
export interface RedisTimeMonitoringInterface {
    // You have access to command (redis method) so you can use the name to monitor it anywhere you want
    // !! To make it work, do not forget to call the callback at some point and return the result out of it.
    monitorOperationTime<T>(command: string, callback: () => Promise<T>): Promise<T>;
}
  • All of those services are optional, so if you do not need any of those logging/monitoring features, simply do not add any service, which will automatically disable this specific logging/monitoring capability.

Redis Client usage

  • After initialization in your app/feature module it's really simple to use
  • Inject redis client in your service
export class AppService {
    constructor(
        @InjectClientProvider() private redis: RedisClient,
    ) {
    }

    async get(): Promise<string> {
        return this.redis.get('special-key');
    }

    async set(val: string): Promise<void> {
        await this.redis.set('special-key', val);
    }

    async del(key: string): Promise<number> {
        return this.redis.del(key);
    }

    async expire(key: string, seconds: number): Promise<number> {
        return this.redis.expire(key, seconds);
    }

    async hget(key: string, field: string): Promise<string | null> {
        return this.redis.hget(key, field);
    }

    async hset(key: string, field: string, value: ValueType): Promise<number> {
        return this.redis.hset(key, field, value);
    }

    async hdel(key: string, field: string): Promise<number> {
        return this.redis.hdel(key, string);
    }

    async hlen(key: string): Promise<number> {
        return this.redis.hlen(key);
    }

    async mget(keys: string[]): Promise<Array<string | null>> {
        return this.redis.mget(keys);
    }

    async mset(mappedValues: Map<string, ValueType>): Promise<'OK'> {
        return this.redis.mset(mappedValues);
    }

    async msetex(mappedValues: Map<string, ValueType>, seconds: number): Promise<void> {
        return this.redis.msetex(mappedValues, seconds);
    }

    async zadd(key: string, score: number, value: number): Promise<number> {
        return this.redis.zadd(key, score, value);
    }

    async eval(script: string, numKeys: number, args: ValueType[]): Promise<unknown> {
        return this.redis.eval(script, numKeys, args);
    }

    async exists(key: string): Promise<boolean> {
        return this.redis.exists(key);
    }

    async ping(value: string): Promise<string> {
        return this.redis.ping(value);
    }

    async publish(channel: string, value: string): Promise<number> {
        return this.redis.publish(channel, value);
    }

    async subscribe(channel: string): Promise<number> {
        return this.redis.subscribe(channel);
    }

    async unsubscribe(channel: string): Promise<number> {
        return this.redis.unsubscribe(channel);
    }

    async onMessage(callback: (channel: string, message: string) => void): Promise<Redis | Cluster> {
        return this.redis.onMessage(callback, message);
    }

    async keys(pattern: string): Promise<string[]> {
        return this.keys(pattern);
    }

    async flushAll(): Promise<void> {
        return this.redis.flushAll()
    }
}

methods description

  • del: deletes a key from Redis.
  • mdel: deletes multiple keys from Redis in a single pipeline.
  • expire: sets a time-to-live (TTL) on a key in Redis.
  • get: retrieves the value of a key in Redis.
  • set: sets the value of a key in Redis.
  • pipeline: allows the client to execute a series of commands in a single pipeline.
  • setex: sets a key with an expiration time in Redis.
  • hget: retrieves the value of a field in a Redis hash.
  • hgetall: retrieves all fields and values of a Redis hash.
  • hset: sets the value of a field in a Redis hash.
  • hlen: retrieves the number of fields in a Redis hash.
  • mget: retrieves the values of multiple keys in Redis.
  • mset: sets the values of multiple keys in Redis.
  • msetex: sets the values of multiple keys with an expiration time in Redis.
  • zadd: adds a value to a Redis sorted set.
  • eval: executes a Lua script on Redis.
  • exists: checks if a key exists in Redis.
  • ping: pings the Redis server.
  • publish: publishes a message to a Redis channel.
  • flushAll: flushes all data from Redis
  • keys: gets all keys from Redis

Readme

Keywords

none

Package Sidebar

Install

npm i @betsys-nestjs/redis

Weekly Downloads

20

Version

5.1.0

License

MIT

Unpacked Size

29.6 kB

Total Files

20

Last publish

Collaborators

  • betsys-development
  • pawelnowak1
  • andrejsoucek
  • jammie88
  • jiraspe2
  • jakubschneller
  • javor454
  • krizacekcz
  • flyrell