Actions
Declare business logic with NEWACTION(), validate its input, expose it as a route and run it from code with ACTION().
On this page
An action is a named piece of business logic. It declares what it accepts (body, URL params, query string), who may run it and what it returns, and it can be exposed as a route or called from your code. Actions are the main way to write the logic of a Total.js 5 application.
// actions/products.js
NEWACTION('products_create', {
name: 'Create a product',
input: '*name:String, price:Number, description:String',
route: '+POST /api/products/',
action: function($, model) {
model.id = UID();
model.dtcreated = NOW;
DATA.insert('products', model).callback($.done(model.id));
}
});Put files with actions in the /actions/ folder (or in a plugin). The framework loads them at start, so NEWACTION() runs once and registers the action under its name. Declaring an action with an existing name replaces the old one.
Declaring an action
NEWACTION(name, options) takes the name and an object of options. You can also pass only the object with an id (or name) property. The action function is required and receives the options object $ and the validated model.
| Option | What it does |
|---|---|
action | function($, model), the logic |
input | Schema of the payload (the body); the validated result is $.model |
output | Schema of the response; the value of $.callback() is cleaned by it |
params | Schema of the dynamic URL parameters ($.params) |
query | Schema of the query string ($.query) |
user | true requires a signed-in user, false requires an anonymous request |
sa / su | Requires a user with the sa or su flag |
permissions | Required permissions, 'products_create,admin' or an array |
route | A route that runs the action, e.g. '+POST /api/products/' |
middleware | Names of middleware to run before the action, 'auth, ratelimit' |
partial | Validates the input partially (only the fields that are sent) |
extend | Puts the response into the payload under this key and returns the payload |
audit | true or a template; writes an audit record after success |
config | Any object; available as $.config |
timeout | Milliseconds; the action fails with Timeout. when it does not respond in time |
cache | true or { query, params, input, user, language, key, expire }; keeps the response in the cache |
oninput | function($), called right before action |
onoutput | function(err, response, $), called after the action responds |
summary | A description of the action; the MCP server uses it as the description of the tool |
mcp | true makes the action a tool of the MCP server |
A schema is an inline definition ('*name:String, email:Email', a * marks a required field) or the name of a registered JSON schema with @ ('@product'). The syntax and the types are described in JSON schemas. When validation fails, the action does not run and the caller receives the errors; errors of query and params are prefixed with query. and params..
The $ object
The first argument of action is an options object, usually named $. It carries the data of the call and the methods that finish it.
NEWACTION('orders_read', {
params: '*id:UID',
query: 'fields:String',
user: true,
action: function($) {
var id = $.params.id;
var user = $.user;
DATA.read('orders').id(id).where('userid', user.id).error(404).callback($);
}
});| Property | What it contains |
|---|---|
$.model | The validated payload (aliases $.payload and $.value) |
$.input | Another alias of $.model |
$.params | The validated URL parameters |
$.query | The validated query string |
$.user | The user of the request, or the user passed to ACTION().user() |
$.config | The config option of the action |
$.id | The name of the running action |
$.controller | The controller of the HTTP request, or undefined |
$.error | The ErrorBuilder of the call |
$.xhr | true for an XHR request, null without a controller |
$.meta | The definition object of the action |
$.env | The value passed to ACTION().env(), or undefined |
$.ip, $.headers, $.url, $.files, $.language, $.ua | Shortcuts to the controller, empty without one |
An action ends with exactly one of these calls:
$.success([value])responds with{ success: true, value: value }.$.callback(value)responds with the value as it is. You can pass$itself as a callback of a database query, for exampleDATA.find('products').callback($).$.done([value])returns afunction(err, response)callback: an error becomes$.invalid(), otherwise it calls$.success(value), or$.success(response)whenvalueistrue.$.invalid(error, [path], [index])fails the call. A number above 399 is an HTTP status ($.invalid(404)); a string is an error message.
$.redirect(url) redirects the HTTP request instead of responding. $.output('html') changes how a route responds (the default is JSON).
$.invalidsafe(message, error) ends the action like $.invalid(message), but it also writes error to the error log. The caller gets only the message, so the details of the error (paths, SQL, addresses) stay on the server. $.throw(error) only writes an error to the log and does not end the action. In an async action an exception that you do not catch ends the call with 500: Internal Server Error and goes to the error log.
NEWACTION('orders_invoice', {
action: async function($) {
try {
var template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');
$.success(template.length);
} catch (e) {
$.invalidsafe('The invoice can\'t be created', e);
}
}
});$.touch([url]) clears the cached state of a static file after you change it (see Static files), the same as TOUCH().
Routes
The route option creates a route for the action. The route string is the same as in Routing: a + before the method requires a signed-in user, a - an anonymous one.
NEWACTION('products_list', {
query: 'search:String, page:Number',
route: 'GET /api/products/',
action: function($) {
var builder = DATA.list('products');
$.query.search && builder.search('name', $.query.search);
builder.paginate($.query.page, 20);
builder.callback($);
}
});A route can also call actions declared elsewhere with -->. The actions run one after another with the same $, and the route returns the response of the action marked (response), or an object with the responses of all actions by name when none is marked.
exports.install = function() {
ROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats');
ROUTE('+API ? +orders_create --> orders_create');
};A + before an action name says that it uses the payload, a - that it does not; without a prefix the input option decides. API routes join many actions under one endpoint (? is the $api endpoint, /api/ by default); see Routing.
route: true is a shortcut for an API ? endpoint named after the action. It becomes +API ? when the action has the user or permissions option.
NEWACTION('account_read', {
user: true,
route: true,
action: function($) {
$.success($.user.name);
}
});Running actions from code
ACTION(name, [payload], [controller]) (alias EXEC) runs one action, or several separated by spaces or commas. It returns a caller; the call starts on the next tick, so you chain its settings first.
ACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) {
if (err)
console.log(err.toString());
else
console.log(response);
});| Method | What it does |
|---|---|
.callback(fn) | function(err, response), or an existing $ that receives the result |
.promise([$]) | Returns a Promise; with $, an error goes to $.invalid() |
.user(user) | Sets $.user (it also accepts a $ and takes its user) |
.query(obj) / .params(obj) | Sets the query string and the URL parameters |
.ctrl(controller) | Runs the action with a controller |
.autorespond() | Sends the response (or the error) to the controller |
.status(fn) | Receives the values the action sends with $.status() |
.progress(fn) | Receives the values the action sends with $.progress() |
.config(obj) | Adds keys to $.config for this call only |
.env(value) | Sets $.env, a value that tells the action where it is called from |
Inside an action, $.action(name, [payload]) runs another action with the same controller (or the same user, query and params when there is none). In a route handler, $.action(name, [model]) (where $ is the controller) does the same with the controller.
NEWACTION('orders_checkout', {
input: '*productid:UID, *count:Number',
user: true,
action: async function($, model) {
var order = await $.action('orders_create', model).promise($);
var payment = await $.action('payments_create', { orderid: order.value }).promise($);
$.success(payment);
}
});After every successful action, the framework emits the event @<name> with ($, response):
ON('@products_create', function($, response) {
console.log($.user.name, 'created', response.value);
});The hooks oninput($) and onoutput(err, response, $) run before the action and after its successful response, so you can prepare data or log results without touching the logic:
NEWACTION('notes_save', {
input: '*body:String',
oninput: function($) {
$.input.body = $.input.body.trim();
},
onoutput: function(err, response, $) {
console.log($.id, 'done', response);
},
action: function($, model) {
$.success(model.body.length);
}
});Caching the response
The cache option keeps the first successful response in the cache. The next calls get a copy of it at once, without running the middleware and the action. List the values that change the response, so each combination gets its own entry: query, params and input take true (all fields of the schema) or a list of fields, user: true keeps one entry per user and language: true one per language. Entries expire after expire (5 minutes by default).
NEWACTION('Products|list', {
query: 'page:Number',
cache: { query: true, key: 'products', expire: '10 minutes' },
action: function($) {
DATA.list('products').page($.query.page, 20).callback($);
}
});
NEWACTION('Products|save', {
input: '*id:UID,*name:String',
action: function($, model) {
DATA.update('products', model).id(model.id).callback(function() {
CACHE.reset('action|products|'); // the next list is read again
$.success();
});
}
});Errors are not cached. Without user, every user gets the same cached response, so do not cache answers that depend on the user without it.
Schemas
NEWSCHEMA(name, callback) groups actions under a common prefix. The callback receives an object whose action(name, options) creates the action <schema>/<name>.
NEWSCHEMA('Products', function(schema) {
schema.action('list', {
route: 'GET /api/products/',
action: function($) {
DATA.find('products').callback($);
}
});
});
// The action name is 'Products/list'Transformations
A transformation is a named chain of functions that change a value. NEWTRANSFORM(name, fn, [id]) adds one function to the chain; TRANSFORM(name, value, [callback]) runs the chain. Every function receives $ and the value, changes $.value and calls $.next().
NEWTRANSFORM('product', function($, value) {
value.name = value.name.trim();
$.next();
}, 'name');
NEWTRANSFORM('product', function($, value) {
$.value = { id: value.id, name: value.name, price: value.price };
$.next();
});
TRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) {
console.log(response); // { id: 1, name: 'Mouse', price: 9 }
});A function can also stop the chain with $.invalid(error); the callback then receives the errors. When you pass an action's $ as the third argument of the Promise form, the errors go to $.invalid() of that action:
NEWACTION('products_read', {
params: '*id:UID',
action: async function($) {
var item = await DATA.read('products').id($.params.id).promise($);
$.callback(await TRANSFORM('product', item, $));
}
});Without a callback, TRANSFORM() returns a Promise, which rejects with the errors of $.invalid() when you do not pass a $. In an action, $.transform(name, value, [callback]) runs it with the controller of the action (and the user of that controller). Put transformations in the /transforms/ folder.