ForgeTotal.js 5
it

Total.js 5

Chiamare un'azione dal tuo codice

Total.js 5 · total5@0.0.19 actions Eseguita con Total.js 5

ACTION(name, payload) restituisce un chiamante che esegue l'azione con tutta la sua validazione, esattamente come se arrivasse da una route. Il secondo argomento è il payload (l'input). Concatena .query() e .user() per darle più dati e termina con .callback(function(err, response) {}) oppure .promise() (da usare con await). Quando i dati non sono validi, err è un error builder invece di un'eccezione.

definitions/math.js
NEWACTION('Math/add', {
	name: 'Add two numbers',
	input: '*a:Number, *b:Number',
	action: function($, model) {
		$.callback({ sum: model.a + model.b });
	}
});
controllers/math.js
exports.install = function() {
	ROUTE('GET /sum/', sum);
	ROUTE('GET /sum-promise/', sum_promise);
};

function sum($) {
	ACTION('Math/add', { a: '2', b: '3' }).callback(function(err, response) {
		if (err)
			$.invalid(err);
		else
			$.json(response);
	});
}

async function sum_promise($) {
	try {
		var response = await ACTION('Math/add', { a: 10, b: 5 }).promise();
		$.json(response);
	} catch (err) {
		$.invalid(400);
	}
}