Skip to content

Commit a3d806d

Browse files
authored
Merge pull request #47 from solanamonk/hydrate_polymorphic_children_from_parent
fix: hydrate polymorphic children from parent
2 parents 0db9b2e + b8c59a1 commit a3d806d

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

src/__tests__/polymorphic.repository.spec.ts

+37
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { resolve } from 'path';
66
import { AdvertRepository } from './repository/advert.repository';
77
import { AbstractPolymorphicRepository } from '../';
88
import { MerchantEntity } from './entities/merchant.entity';
9+
import { UserRepository } from './repository/user.repository';
910

1011
describe('AbstractPolymorphicRepository', () => {
1112
let connection: DataSource;
@@ -230,4 +231,40 @@ describe('AbstractPolymorphicRepository', () => {
230231
});
231232
});
232233
});
234+
235+
describe('Parent', () => {
236+
describe('findOne', () => {
237+
it('Can find parent entity with children', async () => {
238+
const repository = AbstractPolymorphicRepository.createRepository(
239+
connection,
240+
UserRepository,
241+
);
242+
const advertRepository = AbstractPolymorphicRepository.createRepository(
243+
connection,
244+
AdvertRepository,
245+
);
246+
247+
const user = await repository.save(new UserEntity());
248+
249+
const advert = await advertRepository.save(
250+
advertRepository.create({
251+
owner: user,
252+
}),
253+
);
254+
255+
let result = await repository.findOne({
256+
where: { id: user.id },
257+
});
258+
259+
result = await repository.hydrateOne(result);
260+
261+
expect(result).toBeInstanceOf(UserEntity);
262+
expect(result?.adverts).toHaveLength(1);
263+
expect(result?.adverts[0]).toBeInstanceOf(AdvertEntity);
264+
expect(result?.adverts[0].id).toBe(advert.id);
265+
expect(result?.adverts[0].entityType).toBe(UserEntity.name);
266+
expect(result?.adverts[0].entityId).toBe(user.id);
267+
});
268+
});
269+
});
233270
});

src/polymorphic.repository.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ export abstract class AbstractPolymorphicRepository<
169169
resultEntities: PolymorphicChildInterface[],
170170
entities: PolymorphicChildInterface[],
171171
) => entities.concat(...resultEntities),
172-
results as PolymorphicChildInterface[],
172+
[] as PolymorphicChildInterface[],
173173
)
174174
: results) as PolymorphicChildInterface | PolymorphicChildInterface[],
175175
};
@@ -193,7 +193,7 @@ export abstract class AbstractPolymorphicRepository<
193193
: {
194194
where: {
195195
[entityIdColumn(options)]: parent[PrimaryColumn(options)],
196-
[entityTypeColumn(options)]: entityType,
196+
[entityTypeColumn(options)]: parent.constructor.name,
197197
},
198198
},
199199
);

0 commit comments

Comments
 (0)