diff --git a/src/bundled.js b/src/bundled.js index 90cf7ee..e082e9e 100644 --- a/src/bundled.js +++ b/src/bundled.js @@ -99,11 +99,40 @@ export function pluckQuery(... fields) { }; } +function containsField(obj, find) { + var args = find.split('.'); + + for (var i = 0; i < args.length; i++) { + if (!obj || !obj.hasOwnProperty(args[i])) { + return false; + } + obj = obj[args[i]]; + } + return true; +} + +function removeField(obj, find) { + var args = find.split('.'); + + for (var i = 0; i < args.length; i++) { + if (!obj || !obj.hasOwnProperty(args[i])) { + return false; + } + if(i === (args.length - 1)) { + obj[args[i]] = undefined; + delete obj[args[i]]; + return true; + } + obj = obj[args[i]]; + } +} + export function remove(... fields) { const removeFields = data => { for(let field of fields) { - data[field] = undefined; - delete data[field]; + if(containsField(data, field)) { + removeField(data, field); + } } }; diff --git a/test/bundled.test.js b/test/bundled.test.js index 16226d7..34ac18c 100644 --- a/test/bundled.test.js +++ b/test/bundled.test.js @@ -21,9 +21,9 @@ const service = app.service('/todos'); describe('Bundled feathers hooks', () => { beforeEach(done => { service.create([ - {id: 1, name: 'Marshall', title: 'Old Man', admin: true}, - {id: 2, name: 'David', title: 'Genius', admin: true}, - {id: 3, name: 'Eric', title: 'Badass', admin: true} + {id: 1, name: 'Marshall', title: 'Old Man', admin: true, updatedBy : { email : 'admin@feathersjs.com', roles : ['admin'] } }, + {id: 2, name: 'David', title: 'Genius', admin: true, updatedBy : { email : 'admin@feathersjs.com', roles : ['admin'] } }, + {id: 3, name: 'Eric', title: 'Badass', admin: true, updatedBy : { email : 'admin@feathersjs.com', roles : ['admin'] } }, ]).then(() => done()); }); @@ -243,6 +243,23 @@ describe('Bundled feathers hooks', () => { done(); }).catch(done); }); + + it('Removes nested fields from result.data object', done => { + service.after({ + get: [ + hooks.remove('updatedBy.roles') + ] + }); + + service.get(1).then(result => { + assert.equal(result.data.updatedBy.roles, undefined); + assert.equal(result.data.updatedBy.email, 'admin@feathersjs.com'); + // Remove the hooks we just added + service.__afterHooks.find.pop(); + service.__afterHooks.find.pop(); + done(); + }).catch(done); + }); }); describe('without params.provider set', () => { @@ -413,7 +430,8 @@ describe('Bundled feathers hooks', () => { id: 2, name: 'David', title: 'Genius', - admin: true + admin: true, + updatedBy : { email : 'admin@feathersjs.com', roles : ['admin']} }); // Remove the hook we just added service.__beforeHooks.find.pop();