blitz-js / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
MIT License
3.88k stars 83 forks source link

Add support for serialising ES6 classes #34

Closed Skn0tt closed 3 years ago

Skn0tt commented 3 years ago

We could try serializing classes similar to typestack/class-transformer.

Skn0tt commented 3 years ago

Seriliasation is easy, but when reviving during deserialisation needs to have the required classes available. This could be made possible by registering all potentially-transmitted classes beforehand so they can then be used during reviving. Reviving should be achievable by replacing the prototype (I guess?) - we should be able to take inspiration from class-transformer on this.

Registering would require the class and a non-conflicting name in case it's ambiguous. Could look like the following:

SuperJSON.registerClass(MyClass) // registers MyClass with identifier "MyClass"

SuperJSON.registerClass(MyDuplicateClass, "MyDuplicateClass1") // registers MyDuplicateClass with identifier "MyDuplicateClass1"
SuperJSON.registerClass(MyDuplicateClass, "MyDuplicateClass2") // registers MyDuplicateClass with identifier "MyDuplicateClass2"

/* the identifiers could be hashed to reduce string length */

To ease DX, registering could be performed in a compile-step (would be great for Blitz I guess).