During development of some nested entities cases like example array of entity, I discovered that TypeScrip is not able recognize types in runtime if they are packed into Array. const t = Reflect.getMetadata("design:type", this, field);
is working fine only for unpacked types. Issue exists on the github a few years https://github.com/microsoft/TypeScript/issues/7169
Because of that I had to resolve my problem different way. I had a few options but providing a path to the Entity was the most promsing.
Here is an example. As we can see members use an array of XYZ interface, which inside has NestedEntity, which should be serialized and deserialized.
class NestedEntity extends BaseEntity<NestedEntity> {
@Property()
value!: number;
}
interface XYZ {
d: {
w: NestedEntity[];
};
}
class MainEntity extends BaseEntity<MainEntity> {
@Property()
somevalue!: string;
@Property<XYZ[]>({
entity: { path: "?/d/w/?" },
})
members!: XYZ[];
}
But it generates another problem. It is easy to do any mistake during path creation - but I'm a big fan of TypeScript typing after 4.0 version. I've prepared a literal type which is checking that.
You can check how it works here:
Playground
Now it is possible to pass array nested entity test:
// Load nested
const checkEntity = await repository.loadEntity(MainEntity, "entity");
expect(checkEntity.members.length).toEqual(2);
await checkEntity.members[0].load();
expect(checkEntity.members[0].value).toEqual(3);
// Not loaded
const t = () => {
return checkEntity.members[1].value;
};
expect(t).toThrow(Error);