From b8c59a1712b242ce214dd31b57469dbf17cee9a3 Mon Sep 17 00:00:00 2001 From: Solanamonk Date: Sun, 11 Feb 2024 17:30:38 +0100 Subject: [PATCH] fix: hydrate polymorphic children from parent --- src/__tests__/polymorphic.repository.spec.ts | 37 ++++++++++++++++++++ src/polymorphic.repository.ts | 4 +-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/__tests__/polymorphic.repository.spec.ts b/src/__tests__/polymorphic.repository.spec.ts index 6a486df..759ab95 100644 --- a/src/__tests__/polymorphic.repository.spec.ts +++ b/src/__tests__/polymorphic.repository.spec.ts @@ -6,6 +6,7 @@ import { resolve } from 'path'; import { AdvertRepository } from './repository/advert.repository'; import { AbstractPolymorphicRepository } from '../'; import { MerchantEntity } from './entities/merchant.entity'; +import { UserRepository } from './repository/user.repository'; describe('AbstractPolymorphicRepository', () => { let connection: DataSource; @@ -172,4 +173,40 @@ describe('AbstractPolymorphicRepository', () => { }); }); }); + + describe('Parent', () => { + describe('findOne', () => { + it('Can find parent entity with children', async () => { + const repository = AbstractPolymorphicRepository.createRepository( + connection, + UserRepository, + ); + const advertRepository = AbstractPolymorphicRepository.createRepository( + connection, + AdvertRepository, + ); + + const user = await repository.save(new UserEntity()); + + const advert = await advertRepository.save( + advertRepository.create({ + owner: user, + }), + ); + + let result = await repository.findOne({ + where: { id: user.id }, + }); + + result = await repository.hydrateOne(result); + + expect(result).toBeInstanceOf(UserEntity); + expect(result?.adverts).toHaveLength(1); + expect(result?.adverts[0]).toBeInstanceOf(AdvertEntity); + expect(result?.adverts[0].id).toBe(advert.id); + expect(result?.adverts[0].entityType).toBe(UserEntity.name); + expect(result?.adverts[0].entityId).toBe(user.id); + }); + }); + }); }); diff --git a/src/polymorphic.repository.ts b/src/polymorphic.repository.ts index 89b2555..55783e6 100644 --- a/src/polymorphic.repository.ts +++ b/src/polymorphic.repository.ts @@ -169,7 +169,7 @@ export abstract class AbstractPolymorphicRepository< resultEntities: PolymorphicChildInterface[], entities: PolymorphicChildInterface[], ) => entities.concat(...resultEntities), - results as PolymorphicChildInterface[], + [] as PolymorphicChildInterface[], ) : results) as PolymorphicChildInterface | PolymorphicChildInterface[], }; @@ -193,7 +193,7 @@ export abstract class AbstractPolymorphicRepository< : { where: { [entityIdColumn(options)]: parent[PrimaryColumn(options)], - [entityTypeColumn(options)]: entityType, + [entityTypeColumn(options)]: parent.constructor.name, }, }, );