From c7caa0a7c17bcc7d2b89ec54b7e631dfae9e5c4b Mon Sep 17 00:00:00 2001 From: Fabien Franzen Date: Tue, 21 Jul 2015 13:33:42 +0200 Subject: [PATCH] Take strict: validate and throw settings into account --- lib/dao.js | 18 +++++++++++++++--- test/manipulation.test.js | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/lib/dao.js b/lib/dao.js index 62e4bb1c..0dd811c0 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -2336,9 +2336,21 @@ DataAccessObject.prototype.updateAttributes = function updateAttributes(data, op data = ctx.data; if (strict) { - var keys = Object.keys(Model.definition.properties); - data = utils.selectFields(keys)(data); - data = removeUndefined(data); + var props = Model.definition.properties; + var keys = Object.keys(data); + var result = {}; + for (var i = 0; i < keys.length; i++) { + key = keys[i]; + if (props[key]) { + result[key] = data[key]; + } else if (strict === 'throw') { + cb(new Error('Unknown property: ' + key)); + return; + } else if (strict === 'validate') { + inst.__unknownProperties.push(key); + } + } + data = removeUndefined(result); } // update instance's properties diff --git a/test/manipulation.test.js b/test/manipulation.test.js index ac4f3c8a..3877f44e 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -491,7 +491,7 @@ describe('manipulation', function () { }); }); - it('should ignore unknown attributes', function(done) { + it('should ignore unknown attributes when strict: true', function(done) { person.updateAttributes({foo:'bar'}, function(err, p) { if (err) return done(err); @@ -503,6 +503,41 @@ describe('manipulation', function () { }); }); }); + + it('should throw error on unknown attributes when strict: throw', function(done) { + Person.definition.settings.strict = 'throw'; + Person.findById(person.id, function(err, p) { + p.updateAttributes({foo:'bar'}, + function(err, p) { + should.exist(err); + err.name.should.equal('Error'); + err.message.should.equal('Unknown property: foo'); + should.not.exist(p); + Person.findById(person.id, function(e, p) { + if (e) return done(e); + should.not.exist(p.foo); + done(); + }); + }); + }); + }); + + it('should throw error on unknown attributes when strict: throw', function(done) { + Person.definition.settings.strict = 'validate'; + Person.findById(person.id, function(err, p) { + p.updateAttributes({foo:'bar'}, + function(err, p) { + should.exist(err); + err.name.should.equal('ValidationError'); + err.message.should.containEql('`foo` is not defined in the model'); + Person.findById(person.id, function(e, p) { + if (e) return done(e); + should.not.exist(p.foo); + done(); + }); + }); + }); + }); it('should allow same id value on updateAttributes', function(done) { person.updateAttributes({id: person.id, name: 'John'},