TypedJSON icon indicating copy to clipboard operation
TypedJSON copied to clipboard

Examples for using with constructor parameters / DI

Open Benny739 opened this issue 8 years ago • 1 comments

Hi,

Are there any examples available, on how to use typedjson with constructor parameters / DI? I thought about using a custom deserializer function for that purpose, but couldn't find any docs or examples.

Thanks

regards Benny

Benny739 avatar Jan 21 '17 07:01 Benny739

Hi, @Benny739

A parameterless constructor by default is required, as TypedJSON will automatically instantiate the deserialized objects. This is satisfied by at least one such call signature, such as:

class DITarget {
    constructor(dependency?: DISource) {
        // ...
    }
}

Note the optional dependency parameter. In cases where it's not possible to have a parameterless constructor signature, an initializer setting must be supplied to JsonObject, such as:

@JsonObject({
    initializer: (sourceObject) => Object.assign(new DITarget(new DISource()), sourceObject)
})
class DITarget {
    constructor(dependency: DISource) {
        // ...
    }
}

However, as per the current release, this functionality has been pretty much just duct-taped to TypedJSON (hence the lack of documentation), and it has its issues:

  1. sourceObject is the raw Object instance from which the object is being deserialized; the implication here is that you'll need to manually deserialize child objects, otherwise they'll end up as simple Object instances (i.e. without any expected methods); this is not a problem with primitive (number/string/boolean) properties, of course
  2. The initializer option is simply not feasible to use, and in many cases requires various workarounds to be applied (such as when a single dependency object is to be injected into multiple deserialized objects)

I perfectly understand this feature has (would have) its valid use-cases, and the new release will contain a more powerful and flexible approach. It's around the clock, I'm currently testing polymorphic object-tree serialization with the new (read: completely revamped) code.

JohnWeisz avatar Jan 23 '17 11:01 JohnWeisz