Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: hydrate polymorphic children from parent #47

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -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);
});
});
});
});
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