Skip to content

Commit

Permalink
Merge pull request #47 from solanamonk/hydrate_polymorphic_children_f…
Browse files Browse the repository at this point in the history
…rom_parent

fix: hydrate polymorphic children from parent
  • Loading branch information
bashleigh authored Mar 29, 2024
2 parents 0db9b2e + b8c59a1 commit a3d806d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
37 changes: 37 additions & 0 deletions src/__tests__/polymorphic.repository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -230,4 +231,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);
});
});
});
});
4 changes: 2 additions & 2 deletions src/polymorphic.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ export abstract class AbstractPolymorphicRepository<
resultEntities: PolymorphicChildInterface[],
entities: PolymorphicChildInterface[],
) => entities.concat(...resultEntities),
results as PolymorphicChildInterface[],
[] as PolymorphicChildInterface[],
)
: results) as PolymorphicChildInterface | PolymorphicChildInterface[],
};
Expand All @@ -193,7 +193,7 @@ export abstract class AbstractPolymorphicRepository<
: {
where: {
[entityIdColumn(options)]: parent[PrimaryColumn(options)],
[entityTypeColumn(options)]: entityType,
[entityTypeColumn(options)]: parent.constructor.name,
},
},
);
Expand Down

0 comments on commit a3d806d

Please sign in to comment.