skip to Main Content

I am trying to upload the session data to redis whenever a user logs in onto my react native app. Im getting this error "Argument of type ‘unknown’ is not assignable to parameter of type ‘RedisKey’.ts(2345)
(property) Document<unknown, any, any>._id?: unknown
This documents _id." On this line -> redis.set(user._id, JSON.stringify(user) as any);

Here is the full code.

require("dotenv").config();
import { Response } from "express";
import { IUser } from "../models/user.model";
import { redis } from "./redis";
import { RedisKey } from "ioredis";
import { ObjectId } from "mongoose";

interface ITokenOptions {
  expires: Date;
  maxAge: number;
  httpOnly: boolean;
  sameSite: "lax" | "strict" | "none" | undefined;
  secure?: boolean;
}

export const sendToken = (user: IUser, statusCode: number, res: Response) => {
  const accessToken = user.SignAccessToken();
  const refreshToken = user.SignRefreshToken();

  //upload session to redis
  redis.set(user._id, JSON.stringify(user) as any);


  //parse environment variables to integrate with fallback values
  const accessTokenExpire = parseInt(
    process.env.ACCESS_TOKEN_EXPIRE || "300",
    10
  );
  const refreshTokenExpire = parseInt(
    process.env.ACCESS_REFRESH_EXPIRE || "1200",
    10
  );

  //options for cookies
  const accessTokenOptions: ITokenOptions = {
    expires: new Date(Date.now() + accessTokenExpire * 1000),
    maxAge: accessTokenExpire * 1000,
    httpOnly: true,
    sameSite: "lax",
  };

  const refreshTokenOptions: ITokenOptions = {
    expires: new Date(Date.now() + refreshTokenExpire * 1000),
    maxAge: refreshTokenExpire * 1000,
    httpOnly: true,
    sameSite: "lax",
  };

  //only sent secure to true in production
  if (process.env.NODE_ENV === "production") {
    accessTokenOptions.secure = true;
  }

  res.cookie("access_token", accessToken, accessTokenOptions);
  res.cookie("refresh_token", refreshToken, refreshTokenOptions);

  res.status(statusCode).json({
    success: true,
    user,
    accessToken,
  });
};

Im expecting the json data to be uploaded onto redis

2

Answers


  1. Argument of type ‘unknown’ is not assignable to parameter of type ‘RedisKey’.

    redis.set(user._id, JSON.stringify(user) as any)

    first lines are error and second line is code, im trying upload session data to redis

    Login or Signup to reply.
  2. use
    const userId = String(user._id); // Safely convert _id to a string
    const userData = JSON.stringify(user); // Serialize the user object

    redis.set(userId, userData); // Store the data in Redis

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search