json2obj-hoc
Higher-Order Component that adds ability for object to be re-constructed from JSON string properly preserving given Class behavior.
Usage
In the class that you want to enhance with this HOC
Then declare your class and at the end export
as Higher-Order Component
// have to make publicKey optional for json2Obj HOC to work // (object must support a constructor with no parameters) { thispublicKey = publicKey thisbalance = 0 thisstake = 0 } // this method defines behavior of Account data type, // which will be preserved after you deserialize the object from JSON { thisbalance += amount } Account // enhancing Account
Wrapping Account
with Json2ObjHOC
adds 2 methods to Account
type.
stringify()
which is self explanatory -- returns JSON string representation of the object.
and
parse(json)
which returns object instance of correct type.
Here are examples how to use the Account
object:
let account = publicKey: 'some public key' // constructor with required parameterconst amount = 100account const jsonAccount = account// jsonAccount will have the right amount // now let's re-created another instance of the Account object from JSON stringconst generatedAccount = // can still call the addBalance method, because the object is of the right typegeneratedAccount console // ----> 200
Future
Currently only synch version is supported. There are plans to include asynch methods at some point.