Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
How to keep an instance of a Class after it JSON.Stringified?

I have this class

class SpaceSession {
  constructor(session) {
    this.sess = session;
  }

  setUserId(userId) {
    // ...
  }

  static async getUserSpaces(userId) {
    // ...
  }

  setSessionSpace(accessToken, spaceIds) {
    // ...
  }
}

I want to store it on redis cache so I need to serialized it in string with JSON.Stringify()

const newSession = new Session(req.session);
newSession.userId = user.id;
storeCacheObject('cache_key', JSON.stringify(newSession));

But after I get the cache value, the object is not an instance of the Session class anymore, it makes me can't access the functions.

I have done JSON.Stringify replacer approach

JSON.stringify(newSession, (key, value) => {
 if (typeof value === 'function') {
   return value.toString();
 }
   return value;
 }),

And toJSON approach

class SpaceSession {
  // just like previous SpaceSession class that I show to you above
  // ...

  toJson() {
    return {
      setUserId: this.setUserId,
      getUserSpaces: this.getUserSpaces,
      setSessionSpace: this.setSessionSpace,
    };
  }
}

But none of them works for me

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda