ForgeTotal.js 5
it

Total.js 5

Raccogli errori con ErrorBuilder, registrali con ERROR() e conserva una traccia di audit con AUDIT()

Total.js 5 · total5@0.0.19 errorsloggingaudit Eseguita con Total.js 5
  • ErrorBuilder raccoglie 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, length li conta, output() li restituisce come array di { error, path, index } e toString() 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 con function(err): quando riceve un errore lo registra con il nome name, e non fa nulla se l'errore è vuoto. ERROR() è lo stesso callback senza nome. Un errore registrato viene stampato nella console, conteggiato in F.stats.error, e gli ultimi dieci sono conservati in F.errors come { error, name, date }.
  • AUDIT($, message, type) aggiunge una riga JSON a logs/audit.log con chi e dove (ip, ua, url e l'utente quando c'è), il message, il type, i params, query e model della richiesta in data, il nome dell'applicazione in app e l'ora in dtcreated. AUDIT('name', $, message, type) scrive invece in logs/name.log.
controllers/reports.js
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);
}