0

For example:

let client1 = new Client(); // it can do client1.connect() and other methods
await redis.hset('client1', JSON.stringify(client1));
client1 = await redis.get('client1');
client1 = JSON.parse(client1);
await client1.connect();

Is it safe that if you were ever to get the value back and JSON.parse() it, that it would still work properly?

atkayla
  • 8,143
  • 17
  • 72
  • 132
  • 2
    [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description) will omit functions and a few other values that will make it difficult to reconstruct if `Client` is anything other than a plain Json object already. In other words, you could store certain class properties in Redis, but `client1.connect()` would definitely not work. – p.s.w.g May 09 '19 at 18:00
  • @p.s.w.g If I did want to store those clients in a Map where each user has their own client (user:client) and have `.connect()` work, but have that same Map available across replicas (which is why I was interested in using Redis for distributed key-value), is there a way to do that? – atkayla May 11 '19 at 01:08
  • 1
    I'm having a hard time thinking of any reason why you'd actually want that. If you're trying to implement an [object pool](https://en.wikipedia.org/wiki/Object_pool_pattern), then the pool should actually exist only in memory. In any case, there will never be a way to share a single *instance* of an object between two servers or processes, you'll have to *clone* the object in some way, at which point, you would just pass the serializable properties from one process and use them to construct a new instance within the other process. – p.s.w.g May 11 '19 at 15:53
  • @p.s.w.g That's exactly what I wanted! Ok, time to learn a new design pattern! Much appreciated. – atkayla May 11 '19 at 16:27

1 Answers1

0

Maybe you can't.

You only get string when you use JSON.stringfy(client), so you can't get client when you use JSON.parse().

You can try without redis:

let client1 = new Client();
const clientStr = JSON.stringify(client1);
client1 = JSON.parse(clientStr);
await client1.connect();
Ryoma
  • 64
  • 1
  • 9