Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda