enesbugrac
enesbugrac

Reputation: 31

Typescript type error while using Redis type

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;

Upvotes: 3

Views: 6347

Answers (1)

Ben
Ben

Reputation: 1371

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();
}

Upvotes: 1

Related Questions