mobxjs / serializr

Serialize and deserialize complex object graphs to and from JSON and Javascript classes
MIT License
766 stars 52 forks source link

`reference` should allow you to remap the object to a different property name #39

Closed agilgur5 closed 7 years ago

agilgur5 commented 7 years ago

My back end returns references with an _id suffix; e.g. a Post object would refer to a user by poster_id. If I use @serializable(reference(User)) poster_id, then the property poster_id would contain the User object instead of the actual id upon deserialization. I'd like to be able to retain both the reference and it's id on the resulting object (Post object should have a poster that is a User object and a poster_id that is equivalent to the identifier of the User object).

alias lets me do @serializable(alias('poster_id', reference(User)) poster, but I still lose the poster_id in that fashion (but perhaps the solution would be to instead change alias)

mweststrate commented 7 years ago

In that case I would suggest to not use reference at all, but keep the primitive, and introduce a getter (or mobx computed) property to resolve the id

agilgur5 commented 7 years ago

a getter/computed wouldn't handle everything that reference does though -- reference looks at the entire JSON when deserializing. A Model getter for this would have to have knowledge of Stores and be able to retrieve from data from a Store. You'd also have to create the User Store, whereas with reference, you may not need to create a User Store at all if that data isn't used elsewhere. That is how some back-end ORMs operate so maybe that does make more sense.

Perhaps a copy function is the simplest building block here (essentially the same as alias, but leaving the initial property as is)?

mweststrate commented 7 years ago

I doubt whether this use case is generic enough to solve generically, maybe a custom factory can solve it non-generically on your case? custom property does indeed not suffice, as it has only access to the single value. But a custom factory on your type has access to the entire context, or a custom variation of reference would probably work as well. https://github.com/mobxjs/serializr/blob/94bd40b4f7a7d5622fd76a1446e477793d64c502/serializr.js#L950