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(repository): belongsTo accessor should return undefined if foreign key is not included #4325

Merged
merged 1 commit into from
Dec 30, 2019
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
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 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',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a link to the issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good suggestion

// 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(
Expand Down