class-hydrator
When you stringify an instance of a typescript class, it loses its class type and it's impossible to use methods of it. And you can't even stringify it if the instance had circular structures.
Introduce class-hydrator. dehydrate
the instance and stringify it. And send it with ajax, websocket, webrtc
to remote machine. Then, hydrate
(restore) it and use it as if it was created in remote machine.
This is my first open-source project for my private project. I hope it also helpful for your projects. Forks, pull-requests and feedbacks are always welcome.
Installation
- It supports only a typescript project. And it requires
emitDecoratorMetadata
,experimentalDecorators
options intsconfig.json
- Install it with npm
$npm install --save class-hydrator
Getting started
Let's create some classes like below.
And create strawberry instance using classes defined above.
;
You cannot serialize strawberry as it is. JSON.stringify(strawberry)
will throw an Error because strawberry
instance
has a circular structure. So, dehydrate it before serializing.
; ; // little verbose// or you can also; // dehydrate is same with Hydrator.dehydrate except there is no namespace. // Which style you choose is entirely up to your favor./* dehydratedStrawberry Object{ _c_: "Strawberry", _i_: 0, weight: 30, seed: Object{ _c_: "Seed", _i_: 1, fruit: "_i_0" } } */;
or you can just
;
And now, suppose that serializedStrawberry have sent to remote browser using websocket or xhr or anything you prefer.
Remote browser can hydrate
(restore) it preserving class types and circular structures.
Before hydrating it, Every classes in Strawberry
should have been provided to Hydrator so as to use the classes for
instantiating in hydrating process..
; Hydrator.provideClasses;dehydratedStrawberry = JSON.parseserializedStrawberry;restoredStrawberry = hydratedehydratedStrawberry, Strawberry;
or you can just
restoredStrawberry = deserializeserializedStrawberry, Strawberry;
You can now use restoredStrawberry.greeting()
or restoredStrawberry.seed.harvest()
.
Decorators
You can refine how the properties in you Class will be Hydrated or Dehydrated with property decorators.
I prepared two decorators, @OnDehydrate()
and @OnHydrate()
.
And also additional @Exclude()
for convenience.
; Hydrator.provideClasses;
@OnDehydrate()
decorator accepts a function which returns new value you want to set when Rectangle is dehydrated.
It is good practice to compress some properties if they can be generated using other properties. Rectangle.elem will
be null when you dehydrate a Rectangle-type object. And restored when being hydrated.
You can hydrate Rectangle
instance as well as dehydrated Rectangle so as to trigger the @OnHydrate()
decorators.
; // rectangle.elem is not ready yet.rectangle = hydraterectangle; // rectangle.elem is now ready.