From f45ce03579db6f7524c4cd4d71b13bc1464062de Mon Sep 17 00:00:00 2001 From: Agnes Lin Date: Fri, 20 Dec 2019 15:48:03 -0500 Subject: [PATCH] fix(repository): belongsto accessor should return undefined if foreign key is not included --- .../acceptance/belongs-to.relation.acceptance.ts | 12 ++++++++++++ .../src/relations/belongs-to/belongs-to-accessor.ts | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/packages/repository-tests/src/crud/relations/acceptance/belongs-to.relation.acceptance.ts b/packages/repository-tests/src/crud/relations/acceptance/belongs-to.relation.acceptance.ts index c7d29d1ceeae..585a9921fb6e 100644 --- a/packages/repository-tests/src/crud/relations/acceptance/belongs-to.relation.acceptance.ts +++ b/packages/repository-tests/src/crud/relations/acceptance/belongs-to.relation.acceptance.ts @@ -93,6 +93,18 @@ export function belongsToRelationAcceptance( expect(result).to.deepEqual(shipment); }); + it('returns undefined 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.be.undefined(); + }); + it('throws EntityNotFound error when the related model does not exist', async () => { const deletedCustomer = await customerRepo.create({ name: 'Order McForder', diff --git a/packages/repository/src/relations/belongs-to/belongs-to-accessor.ts b/packages/repository/src/relations/belongs-to/belongs-to-accessor.ts index 25490685687c..adebd1075d45 100644 --- a/packages/repository/src/relations/belongs-to/belongs-to-accessor.ts +++ b/packages/repository/src/relations/belongs-to/belongs-to-accessor.ts @@ -53,6 +53,12 @@ export function createBelongsToAccessor< const primaryKey = meta.keyTo; const sourceModel = await sourceRepository.findById(sourceId); const foreignKeyValue = sourceModel[foreignKey as keyof Source]; + // workaround to check referential integrity. + // should be removed once the memory connector ref integrity is done + // GH issue: https://github.com/strongloop/loopback-next/issues/2333 + if (!foreignKeyValue) { + return (undefined as unknown) as Target; + } // eslint-disable-next-line @typescript-eslint/no-explicit-any const constraint: any = {[primaryKey]: foreignKeyValue}; const constrainedRepo = new DefaultBelongsToRepository(