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