Skip to content

Commit 68a9238

Browse files
ryanxwelchdigitalsadhu
authored andcommitted
fix(serializer): remove duplicate includes from serializer
Proposed resolution to the following issue: #111
1 parent 6f71beb commit 68a9238

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

lib/serializer.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,25 @@ function handleIncludes (resp, includes, relations, app) {
379379
})
380380

381381
if (embedded.length) {
382-
resp.included = _.flattenDeep(embedded)
382+
// This array may contain duplicate models if the same item is referenced multiple times in 'data'
383+
let duplicate = _.flattenDeep(embedded)
384+
// So begin with an empty array that will only contain unique items
385+
let unique = []
386+
// Iterate through each item in the first array
387+
duplicate.forEach(function(d){
388+
// Count the number of items in the unique array with matching 'type' AND 'id'
389+
// Since we're adhering to the JSONAPI spec, both 'type' and 'id' can assumed to be present
390+
// Both 'type' and 'id' are needed for comparison because we could theoretically have objects of different
391+
// types who happen to have the same 'id', and those would not be considered duplicates
392+
let count = unique.filter(function(u){
393+
return (u.type === d.type) && (u.id === d.id)
394+
}).length;
395+
// If there are no matching entries, then add the item to the unique array
396+
if (count === 0) {
397+
unique.push(d)
398+
}
399+
})
400+
resp.included = unique
383401
}
384402
}
385403

0 commit comments

Comments
 (0)