Skip to content

Commit 7b1f53a

Browse files
committed
Merge pull request #53 from robertdp/fix-relation-loading
Avoid loading belongsTo relations with falsey keys
2 parents e063a27 + 8791590 commit 7b1f53a

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

src/index.js

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -159,27 +159,33 @@ function loadWithRelations (items, resourceConfig, options) {
159159
})
160160
} else if (def.type === 'belongsTo' || (def.type === 'hasOne' && def.localKey)) {
161161
if (instance) {
162-
task = this.find(resourceConfig.getResource(relationName), DSUtils.get(instance, def.localKey), __options).then(relatedItem => {
163-
instance[def.localField] = relatedItem
164-
return relatedItem
165-
})
162+
let id = DSUtils.get(instance, def.localKey)
163+
if (id) {
164+
task = this.find(resourceConfig.getResource(relationName), DSUtils.get(instance, def.localKey), __options).then(relatedItem => {
165+
instance[def.localField] = relatedItem
166+
return relatedItem
167+
})
168+
}
166169
} else {
167-
task = this.findAll(resourceConfig.getResource(relationName), {
168-
where: {
169-
[relationDef.idAttribute]: {
170-
'in': DSUtils.filter(items.map(function (item) { return DSUtils.get(item, def.localKey) }), x => x)
171-
}
172-
}
173-
}, __options).then(relatedItems => {
174-
DSUtils.forEach(items, item => {
175-
DSUtils.forEach(relatedItems, relatedItem => {
176-
if (relatedItem[relationDef.idAttribute] === item[def.localKey]) {
177-
item[def.localField] = relatedItem
170+
let ids = DSUtils.filter(items.map(function (item) { return DSUtils.get(item, def.localKey) }), x => x)
171+
if (ids.length) {
172+
task = this.findAll(resourceConfig.getResource(relationName), {
173+
where: {
174+
[relationDef.idAttribute]: {
175+
'in': ids
178176
}
177+
}
178+
}, __options).then(relatedItems => {
179+
DSUtils.forEach(items, item => {
180+
DSUtils.forEach(relatedItems, relatedItem => {
181+
if (relatedItem[relationDef.idAttribute] === item[def.localKey]) {
182+
item[def.localField] = relatedItem
183+
}
184+
})
179185
})
186+
return relatedItems
180187
})
181-
return relatedItems
182-
})
188+
}
183189
}
184190
}
185191

0 commit comments

Comments
 (0)