Skip to content

Commit

Permalink
Relax the validation requirements for dates.
Browse files Browse the repository at this point in the history
Ensure that `#propertyTypes()` accounts for optional properties.
  • Loading branch information
Kit Cambridge committed Jul 10, 2013
1 parent cf7606f commit 772bea8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/polyclay.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(); }
});

Expand Down Expand Up @@ -195,16 +195,17 @@ 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))
{
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;
Expand Down Expand Up @@ -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++)
Expand Down
10 changes: 10 additions & 0 deletions test/test-01-polyclay.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}; };
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit 772bea8

Please sign in to comment.