ForgeTotal.js 5
en

Total.js 5

Call an action from your own code

Total.js 5 · total5@0.0.19 actions Executed against Total.js 5

ACTION(name, payload) returns a caller that runs the action with all its validation, exactly as if it came from a route. The second argument is the payload (the input). Chain .query() and .user() to give it more data, and finish with .callback(function(err, response) {}) or .promise() (use it with await). When the data is invalid, err is an error builder instead of an exception.

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);
	}
}