deepkit-framework icon indicating copy to clipboard operation
deepkit-framework copied to clipboard

[Feature] Serialization Consistency for Optional Properties

Open Char2sGu opened this issue 2 years ago • 3 comments

This is for a API pattern which keeps the consistency of fields, where every fields should be returned in the response no matter whether there is a value.

Currently the serialization behavior of optional fields varies based on whether the field is a constructor param:

test('null serialization consistency', async () => {
    {
        class MyEntity {
            id: number & PrimaryKey & AutoIncrement = 0;
            constructor(public name?: string) {}
        }
        const entity = new MyEntity();
        expect(serialize<MyEntity>(entity)).toEqual({ id: 0, name: null }); // PASS
    }
    {
        class MyEntity {
            id: number & PrimaryKey & AutoIncrement = 0;
            name?: string;
        }
        const entity = new MyEntity();
        expect(serialize<MyEntity>(entity)).toEqual({ id: 0, name: null }); // FAIL
    }
});

Char2sGu avatar Aug 20 '22 10:08 Char2sGu

I think undefined would be more correct

timvandam avatar Aug 20 '22 10:08 timvandam

I think undefined would be more correct

JSON.stringify() does not support undefined, they will be directly ignored

Char2sGu avatar Aug 21 '22 01:08 Char2sGu

I think the behaviour here is changed because when you do new MyEntity with the constructor property, it will actually set the property to the prototype, not matter if undefined or not (this.name = name), and with the non-constructor property it won't be visible in the prototype since no property assignment happens. The serializer uses the in operator to check if the property is known and if not known it simply does not output it. Definitely unfortunate, but I don't know a solution right know. If you have any ideas, let me know.

marcj avatar Dec 02 '22 07:12 marcj