added human readable errors

This commit is contained in:
Ritchie Martori
2012-03-26 17:48:39 -07:00
parent 55752ac596
commit f78778a9b4
2 changed files with 41 additions and 4 deletions

View File

@@ -49,11 +49,47 @@ module.exports = function (req, res, next) {
// validate JSON
validation = revalidator.validate(req.body, resource);
err = validation.valid ? err : validation;
err = validation.valid ? err : transform(validation);
next(err);
} else {
// continue
next(err);
}
}
}
/**
* Transform revalidator errors into human redable errors.
*/
function transform(validation) {
var err = {}
, errors = validation.errors
, e
, prop
;
for(var i = 0, len = errors.length; i < len; i++) {
e = errors[i];
prop = e.property;
switch(e.attribute) {
case 'type':
err[prop] = 'must be a ' + e.expected;
break;
case 'required':
err[prop] = 'is required';
break;
default:
err[prop] = 'is not valid'
break;
}
}
// rename and add human readable errors
validation.validation = validation.errors;
validation.errors = err;
return validation;
}

View File

@@ -12,10 +12,11 @@ describe('Resource Actions', function(){
describe('POST /todos', function(){
it('should return an error when provided invalid data', function(done) {
todos.post({title: 123}, function (err, todo, req, res) {
todos.post({foo: 123, completed: 'flarg'}, function (err, todo, req, res) {
expect(err).to.exist;
expect(err.valid).to.equal(false);
expect(err.errors).to.have.length(1);
expect(err.validation).to.have.length(2);
expect(err.errors).to.be.a('object');
expect(todo).to.not.exist;
done();
})