ForgeTotal.js 5
en

Total.js 5

Expose actions through one API endpoint

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

An API route publishes actions under one URL. The client always sends POST with a JSON body { "schema": "name", "data": { ... } }, and Total.js dispatches it to the action registered for that name. One URL, many operations: it is the style that jComponent's API() function speaks.

The prefix of the name decides what happens to data:

  • +name: the input of the action is required and validated
  • -name: the action takes no input
  • %name: partial input (for patches)
definitions/math.js
NEWACTION('Math/add', {
	name: 'Add two numbers',
	input: '*a:Number, *b:Number',
	action: function($, model) {
		$.callback({ sum: model.a + model.b });
	}
});

NEWACTION('Math/time', {
	name: 'Server time',
	action: function($) {
		$.callback({ year: new Date().getFullYear() });
	}
});
controllers/api.js
exports.install = function() {
	ROUTE('API /api/ +math_add --> Math/add');
	ROUTE('API /api/ -math_time --> Math/time');
};