mirror of
https://github.com/zhigang1992/deployd.git
synced 2026-06-05 06:40:37 +08:00
added human readable errors
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user