Skip to content

Commit

Permalink
fix(repository): belongsto accessor should return empty if foreign ke…
Browse files Browse the repository at this point in the history
…y is not included
  • Loading branch information
Agnes Lin committed Dec 20, 2019
1 parent 9fee3f3 commit f904724
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,18 @@ export function belongsToRelationAcceptance(
expect(result).to.deepEqual(shipment);
});

it('returns an empty array if the source instance does not have the foreign key', async () => {
await shipmentRepo.create({
name: 'Tuesday morning shipment',
});
const order = await orderRepo.create({
// doesn't have the foreign key
description: 'Order that is shipped Tuesday morning',
});
const result = await orderRepo.shipment(order.id);
expect(result).to.deepEqual([]);
});

it('throws EntityNotFound error when the related model does not exist', async () => {
const deletedCustomer = await customerRepo.create({
name: 'Order McForder',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ export function createBelongsToAccessor<
const primaryKey = meta.keyTo;
const sourceModel = await sourceRepository.findById(sourceId);
const foreignKeyValue = sourceModel[foreignKey as keyof Source];
// different dbs use different empty values
if (foreignKeyValue === undefined || foreignKeyValue === null) {
return ([] as unknown) as Target;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const constraint: any = {[primaryKey]: foreignKeyValue};
const constrainedRepo = new DefaultBelongsToRepository(
Expand Down

0 comments on commit f904724

Please sign in to comment.