Created
June 19, 2017 17:48
-
-
Save luizcarraro/2c88306eed1613df4037967e2244af7b to your computer and use it in GitHub Desktop.
Custom sails badrequest response for ember processing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 400 (Bad Request) Handler | |
* | |
* Usage: | |
* return res.badRequest(); | |
* return res.badRequest(data); | |
* return res.badRequest(data, 'some/specific/badRequest/view'); | |
* | |
* e.g.: | |
* ``` | |
* return res.badRequest( | |
* 'Please choose a valid `password` (6-12 characters)', | |
* 'trial/signup' | |
* ); | |
* ``` | |
*/ | |
module.exports = function badRequest(data) { | |
// Get access to `req`, `res`, & `sails` | |
var req = this.req; | |
var res = this.res; | |
var sails = req._sails; | |
// Set status code | |
res.status(400); | |
// Log error to console | |
if (data !== undefined) { | |
sails.log.verbose('Sending 400 ("Bad Request") response: \n',data); | |
} | |
else sails.log.verbose('Sending 400 ("Bad Request") response'); | |
// console.log(data.Errors) | |
if(data.Errors) return res.jsonx({errors: _processError(data.Errors)}); | |
if(data.message) return res.jsonx(data.message) | |
return res.jsonx(data) | |
}; | |
function _processError(validationError) { | |
var validation_response = []; | |
Object.keys(validationError).forEach(function(validation_field) { | |
if (validationError[validation_field]) { | |
var processField = validationError[validation_field]; | |
processField.forEach(function(rule) { | |
console.log('rule: ' + rule.rule) | |
if (rule.message !== 'default') { | |
validation_response.push({ | |
detail: rule.message | |
}); | |
} | |
}); | |
} | |
}); | |
return validation_response; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment