Skip to content

Commit

Permalink
Fixed validation utils
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Buczynski committed Jun 11, 2016
1 parent 09d9beb commit 5da5b05
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 24 deletions.
33 changes: 18 additions & 15 deletions app/error/middleware/log-to-console.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,34 @@ let ValidationError = require('../type/client/validation');
*/
module.exports = function(error, req, res, next) {

//Log validation errors differently
if (error instanceof ValidationError && error.data && error.data.fields) {
console.log(chalk.red(
error.name + (error.message ? (': ' + error.message) : '')
));
let fields = error.data.fields;
for (let field in fields) {
if (fields.hasOwnProperty(field)) {
console.log(chalk.red(' - ', field + ':', fields[field].message));
}
}
}

//Log stack if present
else if (error.stack) {
if (error.stack) {
console.log(chalk.red(error.stack));
}

//Log error name and code
//Log error name and message
else {
console.log(chalk.red(
error.name + (error.message ? (': ' + error.message) : '')
));
}

//Log validation errors fields
if (error instanceof ValidationError && error.data && error.data.fields) {
let fields = error.data.fields;
let lines = [];
for (let field in fields) {
if (fields.hasOwnProperty(field)) {
let message = fields[field].message || fields[field].type;
lines.push(chalk.red(' - ', field + ':', message));
}
}
if (lines.length) {
console.log(chalk.red('\nFields:'));
lines.forEach(line => console.log(line));
}
}

//Call next middleware
next(error);
};
18 changes: 9 additions & 9 deletions app/utils/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,24 @@ module.exports = {
/**
* Create field error helper for use in data validation promise chains
*/
fieldError(field, type) {
return {field, type};
fieldError(field, type, message) {
return {field, type, message};
},

/**
* Find field errors helper for use in promise chains
*/
findFieldErrors(results) {
let errors = {};
getErroredFields(results) {
let fields = {};
results.forEach(result => {
if (result && result.field && result.type) {
let field = result[0];
let type = result[1];
errors[field] = {type};
let {field, type, message} = result;
fields[field] = {type, message};
}
});
if (Object.keys(errors).length > 0) {
throw errors;
if (Object.keys(fields).length > 0) {
return fields;
}
return null;
}
};

0 comments on commit 5da5b05

Please sign in to comment.