Redis Configuration

PHOTO EMBED

Mon Sep 05 2022 13:32:00 GMT+0000 (Coordinated Universal Time)

Saved by @atharlaique #javascript #nodejs

const redisClient = require('redis')
const logger = require('../services/Logger')

const ENV = process.env.ENV ? process.env.ENV : 'DEV'

class Redis {
    constructor() {
        this.client = redisClient.createClient({
            url: process.env.REDIS_URL
        })

        // create connection
        this.client.connect()
        logger.info(`Redis connection opened`)
        // get some connection diagnostics
        this.client
            .sendCommand(['CLIENT', 'LIST'])
            .then(list => {
                const clients = list.split('\n')
                logger.info(
                    `Redis client count: ${
                        clients.filter(x => x?.length > 0).length
                    }`
                )
            })
            .catch(err => logger.error(err))
    }

    /**
     * Stores key value pair in redis
     * @param {String} key
     * @param {String} value JSON stringified value
     */
    async put(key, value, ttl) {
        const options = {}
        if (ttl) {
            options.EX = ttl
        }
        await this.client.set(
            `${ENV}:${key}`,
            JSON.stringify(value),
            options
        )
    }

    /**
     * Get redis data by key
     * @param {String} key
     * @returns
     */
    async get(key) {
        // logger.info(`getting redis key: ${ENV}:${key}`)
        let data = await this.client.get(`${ENV}:${key}`)

        data = data ? JSON.parse(data) : undefined
        if (data && Object.keys(data).length === 0) data = undefined

        if (!data) {
            logger.info(`Redis cache miss on key ${ENV}:${key}`)
        }
        return data
    }

    /**
     * Remove cache entry
     * @param {String} key
     */
    async clear(key) {
        await this.client.del(`${ENV}:${key}`)
        logger.info(`Redis key: ${key} deleted`)
    }

    /**
     * Delete keys in wild card fashion
     * @param {String} pattern Example: h?llo, h*llo
     */
    async deleteKeysViaWildCardPattern(pattern) {
        logger.info(`Deleting redis keys for pattern: ${pattern}`)
        let cursorIndex = '0'
        let running = true
        do {
            const { cursor, keys } = await this.client.scan(
                cursorIndex,
                {
                    MATCH: `${ENV}:${pattern}`
                }
            )
            logger.info(`Deleting redis keys: ${keys}`)
            // Delete redis key
            keys.forEach(async key => {
                await this.client.del(`${key}`)
                logger.info(`Redis key: ${key} deleted`)
            })

            // update cursor
            cursorIndex = cursor

            // loop control variable
            if (!cursor) running = false
        } while (running)
    }

    /**
     * Set expiry time of the key in milliseconds
     * @param {*} key
     * @param {*} expiryTime
     */
    async setKeyExpireTime(key, expiryTime) {
        await this.client.expire(`${ENV}:${key}`, expiryTime)
    }

    async quit() {
        await this.client?.quit()
    }
}

module.exports = new Redis()
content_copyCOPY