Collect errors with ErrorBuilder, log them with ERROR() and keep an audit trail with AUDIT()
ErrorBuildercollects errors.push(message, [path], [index])adds one (pathis the field it belongs to),push(404)adds the text of a status code and sets the status of the answer,lengthcounts them,output()returns them as an array of{ error, path, index }andtoString()joins the messages.$.invalid(builder)answers with that array and the status of the builder (400 unless a status code was pushed).SUCCESS(value)returns the object for a successful operation:{ success: true, value: value }.ERROR(name)returns a callback forfunction(err)APIs: when it receives an error it records it undername, and it does nothing when the error is empty.ERROR()is the same callback without a name. A recorded error is printed to the console, counted inF.stats.error, and the last ten are kept inF.errorsas{ error, name, date }.AUDIT($, message, type)appends one JSON line tologs/audit.logwith who and where (ip,ua,url, and the user when there is one), themessage, thetype, theparams,queryandmodelof the request indata, the name of the application inappand the time indtcreated.AUDIT('name', $, message, type)writes tologs/name.loginstead.
exports.install = function() {
ROUTE('GET /builder/', builder);
ROUTE('GET /builder404/', builder404);
ROUTE('GET /success/', success);
ROUTE('GET /error/', error);
ROUTE('GET /audit/', audit);
ROUTE('GET /audit-read/{name}/', auditread);
};
function builder($) {
const errors = new ErrorBuilder();
errors.push('Name is required', 'name');
errors.push('Age is too low', 'age', 2);
$.invalid(errors);
}
function builder404($) {
const errors = new ErrorBuilder();
errors.push(404);
$.invalid(errors);
}
function success($) {
$.json(SUCCESS('saved'));
}
function error($) {
const before = F.stats.error;
ERROR('mypart')('Something broke');
ERROR('mypart')(null);
ERROR()('Without a name');
$.json({ counted: F.stats.error - before, last: F.errors.slice(-2).map(n => ({ error: n.error, name: n.name || null, date: n.date instanceof Date || typeof n.date === 'string' })) });
}
function audit($) {
AUDIT($, 'Opened the report', 'info');
AUDIT('security', $, 'Checked the access');
$.json({ ok: true });
}
function auditread($) {
setTimeout(function() {
const lines = require('fs').readFileSync(PATH.logs($.params.name + '.log'), 'utf8').trim().split('\n');
$.json(lines.map(n => JSON.parse(n)));
}, 300);
}