Reducers should be able to clean non-existent nested fields and not fail

This commit is contained in:
Berislav 2018-06-12 10:13:01 +02:00
parent 61be684585
commit 84567fc3dc
3 changed files with 26 additions and 2 deletions

4
lib/query/reducers/lib/cleanReducerLeftovers.js Normal file → Executable file
View file

@ -43,7 +43,7 @@ function cleanNestedFields(parts, results) {
if (parts.length === 1) {
results.forEach(result => {
if (fieldName !== '_id') {
if (_.isObject(result) && fieldName !== '_id') {
delete result[fieldName];
}
});
@ -55,7 +55,7 @@ function cleanNestedFields(parts, results) {
cleanNestedFields(parts, results.map(result => result[fieldName]));
results.forEach(result => {
if (_.keys(result[fieldName]).length === 0) {
if (_.isObject(result[fieldName]) && _.keys(result[fieldName]).length === 0) {
if (fieldName !== '_id') {
delete result[fieldName];
}

View file

@ -42,4 +42,17 @@ Posts.addLinks({
}
}
}
});
Posts.addReducers({
reducerNonExistentNestedField: {
body: {
nested: {
title: 1,
}
},
reduce(object) {
return object.nested ? object.nested.title : 'null';
}
},
});

View file

@ -267,4 +267,15 @@ describe('Reducers', function() {
const data = query.fetch();
assert.isTrue(data.length > 0);
});
it('Should allow non-existent nested fields while cleaning', function() {
const query = createQuery({
posts: {
reducerNonExistentNestedField: 1,
},
});
const data = query.fetch({limit: 1});
assert.equal(data[0].reducerNonExistentNestedField, 'null');
});
});