JohnWeisz/TypedJSON

Allow lazily define type in annotations

Neos3452 opened this issue · 6 comments

Currently, it is hard to define polymorphic subtypes because they result in a circular dependency. A solution to that is to call decorator manually instead of using it as an annotation. See spec/polymorphism-root-abstract-class.spec.ts.

Solution would be to allow types to be defined in a function that would be evaluated when the types are needed instead of in a decorator immediately:

@jsonMember(() => String)
prop: string;

Then the arrow function would be called during deserialisation/serialisation process.

I very much like this approach and am currently stumbling across this problem as well :-).
FYI, the ORM-framework typeorm uses the same approach for specifying relations between classes:

@Entity()
export class User {
    @OneToMany(() => Photo, photo => photo.user)
    photos: Photo[];
}

@Entity()
export class Photo {
    @ManyToOne(() => User, user => user.photos)
    user: User;
}

I already had one go at it, but the main challange is that TypedJSON in the current form processes everything eagerly, and stores the result. Unfortunately, it is not as easy as switching a value for an arrow function :(. Maybe I could give it another go this weekend.

Anyway, have you seen the test I mentioned? It should be good enough if you have only few classes with that problem. What you can do is have an additional file that imports all the subclasses and calls the decorator explicitly for the parent class to keep it tidy.

@Neos3452, it's been longer than I hoped but I should have some time soon to work on typed-json too.

@Neos3452, thanks for the reference to the test. That helped me a lot in implementing a work-around :-). If you find some time to implement a prototype, I'll be more than happy to try it out and give my feedback

Hi @sumbricht, I was able to get a working prototype, but a question popped-into my mind. Do you have a problem with knownTypes for polymorphic deserialisation? Or do you have a problem with defining a type for @jsonMember and friends? Maybe, you could paste a simplified example of you problem?

@MatthiasKunnen, great to have you back 😊. You can take a look at the prototype (and I am emphasising this, as it was hacked as a POC 😁) at the "lazy_types" branch.

@Neos3452, I'll have a look and might work on something related to it.