From 772bea8a4399d289afa9fb568ce8c7d98188861f Mon Sep 17 00:00:00 2001 From: Kit Cambridge Date: Wed, 10 Jul 2013 11:33:49 -0700 Subject: [PATCH] Relax the validation requirements for dates. Ensure that `#propertyTypes()` accounts for optional properties. --- lib/polyclay.js | 11 ++++++----- test/test-01-polyclay.js | 10 ++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/polyclay.js b/lib/polyclay.js index cfc2e9a..b4e6890 100644 --- a/lib/polyclay.js +++ b/lib/polyclay.js @@ -114,7 +114,7 @@ PolyClay.addType( PolyClay.addType( { name: 'date', - validatorFunc: _.isDate, + validatorFunc: function(val) { return _.isDate(val) || isFinite(+val) || isFinite(new Date(val)); }, defaultFunc: function() { return new Date(); } }); @@ -195,9 +195,7 @@ PolyClay.Model.addProperty = function(obj, propname, type) var setterFunc = function(newval) { - if ((obj.prototype.__types[propname] === 'date') && (_.isString(newval) || _.isNumber(newval))) - newval = new Date(newval); - else if ((obj.prototype.__types[propname] === 'string') && (null === newval)) + if ((obj.prototype.__types[propname] === 'string') && (null === newval)) newval = ''; if (!PolyClay.validate[obj.prototype.__types[propname]](newval)) @@ -205,6 +203,9 @@ PolyClay.Model.addProperty = function(obj, propname, type) throw(new Error(propname+': type of '+newval+' not '+obj.prototype.__types[propname])); } + if ((obj.prototype.__types[propname] === 'date') && !_.isDate(newval)) + newval = new Date(newval); + this.__attributesPrev[propname] = this.__attributes[propname]; this.__attributes[propname] = newval; this.__dirty = true; @@ -353,7 +354,7 @@ PolyClay.Model.prototype.serialize = function() PolyClay.Model.prototype.propertyTypes = function() { - var props = this.__properties; + var props = _.union(this.__optional, this.__properties); var result = {}; for (var i = 0; i < props.length; i++) diff --git a/test/test-01-polyclay.js b/test/test-01-polyclay.js index f5aa073..7d87095 100644 --- a/test/test-01-polyclay.js +++ b/test/test-01-polyclay.js @@ -247,6 +247,14 @@ describe('polyclay', function() obj.timestamp.should.be.a('date'); }); + it('date setters parse ISO 8601-style strings', function() + { + var DateModel = polyclay.Model.buildClass({ properties: { timestamp: 'date' } }); + var obj = new DateModel(); + obj.timestamp = '2013-07-10T17:59:03.628Z'; + obj.timestamp.should.be.a('date'); + }); + it('requires that references be strings', function() { var badSetter = function() { instance.pointer_id = {}; }; @@ -352,8 +360,10 @@ describe('polyclay', function() { var notAString = function() { instance.name = 0; }; var notANumber = function() { instance.count = "four"; }; + var notADate = function() { instance.created = 'Invalid Date'; }; notAString.should.throw(Error); notANumber.should.throw(Error); + notADate.should.throw(Error); }); it('setting a property marks the model dirty', function()