Home > Software engineering >  Redis class client is closed
Redis class client is closed

Time:02-02

this is my Redis.ts

import { createClient } from "redis";

class RedisClient {
  client;

  constructor() {
    this.client = createClient();
    this.client.on("connect", (connect) =>
      console.log("Redis Client connected", connect)
    );
  }

  set = async (key: string, value: any) => {
    await this.client.set(key, value);
  };

  get = async (key: string) => {
    return await this.client.get(key);
  };

  disconnect = async () => {
    await this.client.disconnect();
  };
}

export const Redis = new RedisClient();

and while exporting Redis class getting error The client is closed This is my VController.ts

import { Redis } from "../utilities/Redis";
import { Request, Response, NextFunction } from "express";
class VController {
index = async (req: Request, res: Response, next: NextFunction) => {    
    Redis.set('user', {name: "somename"});
    console.log(Redis);
    // more code goes here...
  };
}

Error return Promise.reject(new errors_1.ClientClosedError()); ^ ClientClosedError: The client is closed

Unable to set value in Redis, Thanks in advance!

CodePudding user response:

You are almost there! According to the documentation, the client needs to be explicitly connected by way of the connect() function in order for the commands to be sent to the target Redis node(s):

class RedisClient {
  // ...
  connect = () => this.client.connect();
  // ...
}

And in your calling code:

// ...
await Redis.connect();
Redis.set('user', {name: "somename"});
// ...
  • Related