From 84567fc3dcddc3ad987d656e26bc207d206cf3ec Mon Sep 17 00:00:00 2001 From: Berislav Date: Tue, 12 Jun 2018 10:13:01 +0200 Subject: [PATCH] Reducers should be able to clean non-existent nested fields and not fail --- lib/query/reducers/lib/cleanReducerLeftovers.js | 4 ++-- lib/query/testing/bootstrap/posts/links.js | 13 +++++++++++++ lib/query/testing/reducers.server.test.js | 11 +++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) mode change 100644 => 100755 lib/query/reducers/lib/cleanReducerLeftovers.js diff --git a/lib/query/reducers/lib/cleanReducerLeftovers.js b/lib/query/reducers/lib/cleanReducerLeftovers.js old mode 100644 new mode 100755 index a8bda76..94caf13 --- a/lib/query/reducers/lib/cleanReducerLeftovers.js +++ b/lib/query/reducers/lib/cleanReducerLeftovers.js @@ -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]; } diff --git a/lib/query/testing/bootstrap/posts/links.js b/lib/query/testing/bootstrap/posts/links.js index 494e43d..f0e28ec 100755 --- a/lib/query/testing/bootstrap/posts/links.js +++ b/lib/query/testing/bootstrap/posts/links.js @@ -42,4 +42,17 @@ Posts.addLinks({ } } } +}); + +Posts.addReducers({ + reducerNonExistentNestedField: { + body: { + nested: { + title: 1, + } + }, + reduce(object) { + return object.nested ? object.nested.title : 'null'; + } + }, }); \ No newline at end of file diff --git a/lib/query/testing/reducers.server.test.js b/lib/query/testing/reducers.server.test.js index 19b0260..36591a8 100755 --- a/lib/query/testing/reducers.server.test.js +++ b/lib/query/testing/reducers.server.test.js @@ -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'); + }); });