redwood icon indicating copy to clipboard operation
redwood copied to clipboard

[RFC]: Add ability to cache arbitrary classes in Service Cache

Open cannikin opened this issue 1 year ago • 0 comments

Summary

This isn't even merged yet: https://github.com/redwoodjs/redwood/pull/6082 but I thought of an enhancement. Right now you can only cache things that survive a round trip through JSON.stringify() and JSON.parse(). But if you followed a certain convention in your a class, you could cache arbitrary class instances as well.

Motivation

I'd love to be able to cache anything and count on it coming back out of the cache in the same format. This is a problem with things like Dates or functions, but especially for instances of custom classes.

Detailed proposal

If a class can serialize itself, and provide a way to instantiate a new instance of itself from the serialized form, then it can survive the JSON.serialize() process.

I propose that the class provide a instance function, toCache(), which provides a serialized version of all of it's internal data/state, as well as an additional key that identifies the name of the class itself. Likewise, it provides a class function fromCache() that can create an instance of itself when given the serialized version.

Here's an example implementation:

class Person {
  static fromCache(...args) {
    return new Person(...args)
  }

  constructor(name, age) {
    this.name = name
    this.age = age
  }

  toCache() {
    return { class: 'Person', name: this.name, age: this.age }
  }
}

So what the cache can do is look for a key class on an object returned from the cache. If it's found, it uses that property and calls fromCache() on a class with that name, passing the remaining arguments to it.

Using this in a cache() call looks like:

const person = new Person('Rob', 44)
person // => Person {name: 'Rob', age: 44}
JSON.stringify(person) // => '{name: "Rob", age: 44}'

const cachedPerson = cache('user-1', () => rob)
cachedPerson // => Person {name: 'Rob', age: 44}

Are you interested in working on this?

  • [X] I'm interested in working on this

cannikin avatar Aug 24 '22 18:08 cannikin