Customize SUCCESS() method
The SUCCESS()
method is the most used method in my Total.js applications. And few developers know that the output of this method can be changed to fit your needs.
How to modify it?
- create a definition file called
overrides.js
global.SUCCESS = function(success, value) {
// Check if the "success" variable is a function
if (typeof(success) === 'function') {
return function(err, value) {
success(err, SUCCESS(err, value));
};
}
var err;
if (success instanceof Error) {
// Is "success" Error?
err = success.toString();
success = false;
} else if (success instanceof ErrorBuilder) {
// Maybe "success" is ErrorBuilder instance
if (success.hasError()) {
err = success.output();
success = false;
} else
success = true;
} else if (success == null)
success = true;
if (err)
return { error: err };
else if (success)
return { ok: true };
else
return { error: 'Repeat your operation.' };
};
Usage examples:
console.log(SUCCESS(true));
// Output: { ok: true }
console.log(SUCCESS(false));
// Output: { error: 'Repeat your operation.' }
console.log(SUCCESS(false));
// Output: { error: 'Error: A bug' }
console.log(SUCCESS(new ErrorBuilder().push('', 'A bug')));
// Output: { error: [ { name: '', error: 'A bug', path: undefined, index: undefined } ] }
// the real purpose is to use it as a response in a controller
function some_controller() {
this.json(SUCCESS(true));
}