JohnWeisz / TypedJSON

Typed JSON parsing and serializing for TypeScript that preserves type information.
MIT License
603 stars 64 forks source link

Unable to propagate current deserialization options in custom deserializer #172

Closed amoscatelli closed 3 years ago

amoscatelli commented 3 years ago

Hi there, thank you for TypedJSON I really love this project.

Yet, as far as I understand, we are missing the ability to propagate current deserialization option/context when using a custom deserializer.

For example :

I use jsonArrayMember annotation on a type and register a custom deserializer function. When starting deserializing I register some ITypedJSONSettings for the TypedJSON instance (knownTypes, nameResolver, typeResolver). When calling the custom deserializer function only the objectMemberValue json is passed as argument (line 300) :

https://github.com/JohnWeisz/TypedJSON/blob/master/src/deserializer.ts

In the custom deserializer I want to delegate further/simpler deserialization steps to the same/previous TypedJSON instance. Even if I wanted to create a new instance I still miss the current configuration/options. I know I can use static/global configuration but I can have multiple configurations at runtime.

I propose to pass 'this' as second argument for the deserializer function :

if (objMemberMetadata.deserializer != null) { revivedValue = objMemberMetadata.deserializer(objMemberValue, this); }

Also I want to change the deserializer signature (JsonMemberMetadata) :

deserializer?: ((json: any, current: Deserializer) => any) | null;

I can make a pull request if you do understand/agree what I do mean.

Also this should also be done for custom serializers.

For now, I resort switching global configuration at runtime but that's really ugly. Please let me know me as soon as possibile.

Neos3452 commented 3 years ago

Hi @amoscatelli, thanks for feedback. I read you issue before, but it slipped my mind to write a reply, sorry about that.

A PR would be great! One small comment, instead of passing TypedJSON internals to the function we should have a proxy function that hides it from a user. Also, instead of passing this directly I would prefer it to be passed inside an object so that the arg list does not grow indefinitely.

amoscatelli commented 3 years ago

https://github.com/JohnWeisz/TypedJSON/pull/174