3

Hi i am trying to use redis on typescript but this code always give me this error. I installed "redis": "^4.0.4", "@types/redis": "^4.0.11". How can i solve this problem?

const idUser: string
Argument of type '[string, (err: any, data: any) => void]' is not assignable to parameter of type '[key: RedisCommandArgument] | [options: CommandOptions<ClientCommandOptions>, key: RedisCommandArgument]'.
  Type '[string, (err: any, data: any) => void]' is not assignable to type '[options: CommandOptions<ClientCommandOptions>, key: RedisCommandArgument]'.
    Type at position 0 in source is not compatible with type at position 0 in target.
      Type 'string' is not assignable to type 'CommandOptions<ClientCommandOptions>'.
        Type 'string' is not assignable to type '{ readonly [symbol]: true; }'.

redis.ts

import { Response, Request, NextFunction } from "express"; 
    import * as redis from "redis";
    import { RedisClientOptions } from "redis";
    const redisClient = redis.createClient({
      url: "127.0.0.1:6379",
      legacyMode: true,
    });
    const isCached = (req: Request, res: Response, next: NextFunction) => {
      const { idUser } = req.params;
      // getting our data by key (id)
      redisClient.get(idUser, (err, data) => {
        if (err) {
          res.status(500).send(err);
        }
        if (data != null) {
          console.log("we Found it in Redis 🟢");
          res.send(data);
        } else {
          console.log("User Not Found 🔴 ");
          // go To ⏭️ function or middleware
          next();
        }
      });
    };
    export default isCached;

1 Answer 1

1

You are passing 2 arguments to the method redisClient.get which accepts only one argument of the following type:

'[key: RedisCommandArgument] | [options: CommandOptions, key: RedisCommandArgument]'

Based on Node Redis documentation, it seems that the get method returns a promise, so I suppose your code should look like this:

const data = await redisClient
  .get(idUser)
  .catch((err) => res.status(500).send(err));
if (data != null) {
  console.log("we Found it in Redis 🟢");
  res.send(data);
} else {
  console.log("User Not Found 🔴 ");
  // go To ⏭️ function or middleware
  next();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.