Skip to content

Instantly share code, notes, and snippets.

@jrgcubano
Created February 16, 2015 02:25
Show Gist options
  • Save jrgcubano/5263ccd6cfd68f4f1cab to your computer and use it in GitHub Desktop.
Save jrgcubano/5263ccd6cfd68f4f1cab to your computer and use it in GitHub Desktop.
Schema Validation using jayschema
var ErrorMapper = require('./ErrorMapper');
var formConverter = require('./formConverter');
var JaySchema = require('jayschema');
var util = require('util');
var js = new JaySchema();
function SchemaValidator (schema) {
return function SchemaValidator (req, res, next) {
js.validate(req.body, schema, function (errors) { //REVIEW
if (errors) {
if (!req.is('json')) {
errors = formConverter(errors, schema, req.body);
}
if (errors.length < 1) {
return next();
} else {
errors = ErrorMapper(errors, schema)
console.error("Validation error:", util.inspect({req: {path: req.path}, errors: errors, data: req.body}, {depth: null}));
res.send(400, errors);
}
} else {
next();
}
});
};
}
exports = module.exports = SchemaValidator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment