Raccogli errori con ErrorBuilder, registrali con ERROR() e conserva una traccia di audit con AUDIT()
ErrorBuilderraccoglie errori.push(message, [path], [index])ne aggiunge uno (pathè il campo a cui appartiene),push(404)aggiunge il testo di un codice di stato e imposta lo stato della risposta,lengthli conta,output()li restituisce come array di{ error, path, index }etoString()unisce i messaggi.$.invalid(builder)risponde con quell'array e lo stato del builder (400 a meno che sia stato aggiunto un codice di stato).SUCCESS(value)restituisce l'oggetto di un'operazione riuscita:{ success: true, value: value }.ERROR(name)restituisce un callback per le API confunction(err): quando riceve un errore lo registra con il nomename, e non fa nulla se l'errore è vuoto.ERROR()è lo stesso callback senza nome. Un errore registrato viene stampato nella console, conteggiato inF.stats.error, e gli ultimi dieci sono conservati inF.errorscome{ error, name, date }.AUDIT($, message, type)aggiunge una riga JSON alogs/audit.logcon chi e dove (ip,ua,urle l'utente quando c'è), ilmessage, iltype, iparams,queryemodeldella richiesta indata, il nome dell'applicazione inappe l'ora indtcreated.AUDIT('name', $, message, type)scrive invece inlogs/name.log.
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);
}