Actions
NEWACTION() options, the $ object, ACTION() callers, NEWSCHEMA() and transformations.
On this page
The functions, options and objects of actions in Total.js 5: NEWACTION() and its options, the $ object passed to an action, the caller returned by ACTION()/EXEC(), NEWSCHEMA(), and NEWTRANSFORM()/TRANSFORM().
For an introduction with examples, read the guide Actions. Schemas for input, output, params and query are described in JSON schemas.
API
method
NEWACTION(name, options)
Declares an action.
NEWACTION(name, options)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the action, e.g. products_create |
options |
Object |
The definition: action, input, output, params, query, user, permissions, route and the other options |
Returns Object The definition of the action
Registers the action under name and returns the definition object. When name is an object, it is the options and the name is taken from its id or name property. An action with the same name is removed first (with its route). The returned object has remove(), which removes the action and its route. All registered actions are in F.actions.
NEWACTION('products_update', {
name: 'Update a product',
params: '*id:UID',
input: '*name:String, price:Number',
permissions: 'products',
route: '+PUT /api/products/{id}/',
action: function($, model) {
DATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id));
}
});
var action = NEWACTION('temp_test', { action: $ => $.success() });
action.remove();
method
ACTION(name, [payload], [controller])
Runs one or more actions from code.
ACTION(name, [payload], [controller])| Parameter | Type | Description |
|---|---|---|
name |
String |
Action name, or names separated by spaces; a + or - prefix says whether the action uses the payload |
payload? |
Object |
The data validated by the input option |
controller? |
Controller |
A controller of an HTTP request |
Returns ActionCaller The caller with callback(), promise(), user() and the other methods
Returns an action caller. The call starts on the next tick, so set the user, query, params and callback by chaining. name can contain several actions separated by spaces or commas; they run in order with the same $. The result is the response of the action marked (response), or an object with the responses of all actions by their names. A single action is always the response. With a controller, the user, query and params are taken from it.
ACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {
console.log(err, response);
});
ACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {
// response is the response of orders_notify
});
method
EXEC(name, [payload], [controller])
An alias of ACTION().
EXEC(name, [payload], [controller])| Parameter | Type | Description |
|---|---|---|
name |
String |
Action name or names |
payload? |
Object |
The payload |
controller? |
Controller |
A controller |
Returns ActionCaller The caller
The same function as ACTION().
var response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();
method
NEWSCHEMA(name, callback)
Groups actions under a common name.
NEWSCHEMA(name, callback)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the schema |
callback |
Function|String |
function(schema), or an inline schema definition |
Returns Object Nothing for a callback; the JSON schema for a string
Calls callback(schema); schema.action(name, options) declares the action <schema name>/<name> with NEWACTION() and returns it. The created actions are also in schema.actions. A leading @ in the name is removed. When the second argument is a string, NEWSCHEMA() registers a JSON schema with that inline definition instead, and returns it.
NEWSCHEMA('Users', function(schema) {
schema.action('read', {
params: '*id:UID',
action: function($) {
DATA.read('users').id($.params.id).error(404).callback($);
}
});
});
ACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log);
NEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');
method
NEWTRANSFORM(name, fn, [id])
Adds a function to a named transformation.
NEWTRANSFORM(name, fn, [id])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the transformation |
fn |
Function |
function($, value) |
id? |
String |
An identifier for removing the function later |
Returns Object An object with id, action and remove()
Functions of one name run in the order they were added. Each receives ($, value); it changes value or assigns a new $.value, then calls $.next(), or stops the chain with $.invalid(error) (the callback of TRANSFORM() then receives the errors). $.user and $.controller are set when the transformation is run with a controller. Returns an object with remove(). NEWTRANSFORM(name, null, id) removes the function with that id.
NEWTRANSFORM('user', function($, value) {
delete value.password;
$.next();
}, 'password');
NEWTRANSFORM('user', null, 'password');
method
TRANSFORM(name, value, [callback], [controller])
Runs a named transformation.
TRANSFORM(name, value, [callback], [controller])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the transformation |
value |
Object |
The value to transform |
callback? |
Function |
function(err, value) |
controller? |
Controller |
A controller; its user is $.user in the functions |
Returns Promise A Promise when there is no callback
Runs all functions added with NEWTRANSFORM(name) and calls callback(err, value) with the final value. A name without functions returns the value unchanged. Without a callback, it returns a Promise and the third argument is the controller. The Promise rejects with the errors of $.invalid(); when the third argument is the $ of an action (or a controller), the errors go to its invalid() instead.
TRANSFORM('user', user, function(err, value) {
console.log(value);
});
var value = await TRANSFORM('user', user);
try {
var value = await TRANSFORM('user', user);
} catch (err) {
console.log(err.toString()); // the errors of $.invalid()
}
event
ON('@' + name, function($, response) {})
Emitted after an action responds successfully.
ON('@' + name, function($, response) {})| Parameter | Type | Description |
|---|---|---|
$ |
Options |
The $ of the action |
response |
Object |
The response of the action |
The event name is @ and the name of the action. It runs after the response, so it is a good place for notifications, statistics or caches. It is not emitted when the action fails.
ON('@orders_create', function($, response) {
console.log('New order', response.value, 'by', $.user.id);
});
config
action: Function
The logic of the action.
action: FunctionReturns Function
function($, model). model is the validated payload (the same as $.model). The function must end the call with $.success(), $.callback(), $.invalid() or a callback from $.done(). It can be async: when its promise rejects (an exception in the function), the call ends with the error 500: Internal Server Error and the exception is written to the error log, so the caller does not wait for a timeout.
NEWACTION('ping', {
action: function($) {
$.success(NOW);
}
});
config
input: String|Object
Schema of the payload.
input: String|ObjectReturns String|Object
An inline schema ('*name:String, email:Email') or the name of a JSON schema with @ ('@product'). The payload is validated and cleaned before the action runs; on failure the action does not run and the caller gets the errors. Without input the payload is not validated. See JSON schemas.
NEWACTION('contact_send', {
input: '*name:String, *email:Email, message:String',
action: function($, model) {
$.success();
}
});
config
output: String|Object
Schema of the response.
output: String|ObjectReturns String|Object
The response is passed through this schema, so only the declared fields leave the action. Use it with $.callback(): with $.success() the schema is applied to the whole { success, value } object.
NEWACTION('users_read', {
params: '*id:UID',
output: 'id:UID, name:String, email:Email',
action: function($) {
DATA.read('users').id($.params.id).callback($);
}
});
config
params: String|Object
Schema of the URL parameters.
params: String|ObjectReturns String|Object
Validates $.params, the dynamic parts of the route ({id}). Errors have the prefix params..
NEWACTION('products_remove', {
params: '*id:UID',
route: '+DELETE /api/products/{id}/',
action: function($) {
DATA.remove('products').id($.params.id).callback($.done());
}
});
config
query: String|Object
Schema of the query string.
query: String|ObjectReturns String|Object
Validates $.query. Errors have the prefix query..
NEWACTION('products_search', {
query: '*q:String, page:Number',
route: 'GET /api/products/search/',
action: function($) {
DATA.find('products').search('name', $.query.q).callback($);
}
});
config
user: Boolean
Requires a signed-in or an anonymous user.
user: BooleanReturns Boolean
true: the action fails with 401 when $.user is empty. false: it fails with 401 when there is a user. The options sa: true or su: true require a user with the sa or su flag.
NEWACTION('account_read', {
user: true,
action: function($) {
$.success($.user);
}
});
config
permissions: String|Array
Required permissions.
permissions: String|ArrayReturns String|Array
A string separated by commas or semicolons, or an array. The user needs at least one of them in user.permissions or user.roles (an array or an object); sa and su users pass always. Otherwise the action fails with 401.
NEWACTION('invoices_remove', {
permissions: 'invoices_remove,admin',
params: '*id:UID',
action: function($) {
DATA.remove('invoices').id($.params.id).callback($.done());
}
});
config
route: String
A route that runs the action.
route: StringReturns String
A route string as in Routing ('+POST /api/products/'). The framework appends --> <name> and creates the route; the option then holds the route object. url is the same option under another name. With encrypt: true the route gets the @encrypt flag.
route: true creates an API ? endpoint named after the action (+API ? when the action has the user or permissions option).
NEWACTION('products_create', {
input: '*name:String',
route: '+POST /api/products/',
action: function($, model) {
$.success();
}
});
NEWACTION('products_list', {
route: '+API ?',
action: function($) {
DATA.find('products').callback($);
}
});
config
middleware: String
Middleware to run before the action.
middleware: StringReturns String
Names of middleware registered with MIDDLEWARE(), separated by spaces, commas or |. Each runs as fn($, next) before the action; a missing middleware is logged and skipped. See Middleware.
NEWACTION('reports_build', {
middleware: 'ratelimit',
action: function($) {
$.success();
}
});
config
partial: Boolean
Validates the input partially.
partial: BooleanReturns Boolean
With true, input validates only the fields present in the payload and does not check required fields. Useful for PATCH updates.
NEWACTION('products_patch', {
params: '*id:UID',
input: '*name:String, *price:Number',
partial: true,
action: function($, model) {
DATA.modify('products', model).id($.params.id).callback($.done());
}
});
config
extend: String
Adds the response to the payload.
extend: StringReturns String
The response is stored in the payload under this key (a path with dots is allowed) and the whole payload becomes the response. Without a payload an empty object is used. Useful in a chain of actions that build one object.
NEWACTION('order_totals', {
extend: 'totals',
action: function($, model) {
$.callback({ count: 3, price: 120 });
}
});
// response: { ...payload, totals: { count: 3, price: 120 } }
config
audit: Boolean|String
Writes an audit record after success.
audit: Boolean|StringReturns Boolean|String
true writes a record without a message; a string is a Tangular template rendered with $ ('{{ $.user.name }} created {{ $.model.name }}'). The record has the user, IP, URL, the action name and the data, and goes to DEF.onAudit (by default the file logs/actions.log).
NEWACTION('products_create', {
input: '*name:String',
audit: '{{ $.user.name }} created {{ $.model.name }}',
action: function($, model) {
$.success();
}
});
config
config: Object
Custom configuration of the action.
config: ObjectReturns Object
Any object; it is available as $.config in the action, so one function can serve several actions.
function list($) {
DATA.find($.config.table).callback($);
}
NEWACTION('products_list', { config: { table: 'products' }, action: list });
NEWACTION('orders_list', { config: { table: 'orders' }, action: list });
config
timeout: Number
since 0.0.16
A time limit of the action.
timeout: NumberReturns Number
In milliseconds. When the action does not respond in time, it fails with the error Timeout.; a later response is ignored.
NEWACTION('reports_export', {
timeout: 10000,
action: function($) {
setTimeout(() => $.success(), 2000);
}
});
config
cache: true | { query, params, input, user, language, key, expire }
Keeps the response of the action in the cache.
cache: true | { query, params, input, user, language, key, expire }Returns Boolean|Object
The first successful response is kept in the cache (CACHE) and the next calls get a copy of it: the middleware and the action do not run. The response is copied both when it is stored and when it is read, so a caller can change its copy safely. Errors are not cached.
With true the action has one cached response. An object makes one entry for each combination of values:
| Key | Value |
|---|---|
query, params, input | true (all fields of the schema of the action) or a comma-separated list of fields |
user | true ($.user.id) or a comma-separated list of keys of $.user |
language | true: one entry for each $.language |
key | A name for the entries; CACHE.reset('action|' + key + '|') removes them |
expire | How long an entry is kept, default '5 minutes' |
Without user, all users share the same cached response.
NEWACTION('Products|list', {
query: 'page:Number,category:String',
cache: { query: true, key: 'products', expire: '10 minutes' },
action: function($) {
DATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($);
}
});
// after a product is saved
CACHE.reset('action|products|');
NEWACTION('Account|profile', {
user: true,
cache: { user: true, expire: '1 minute' },
action: function($) {
DATA.read('users').id($.user.id).callback($);
}
});
config
summary: String
A description of the action.
summary: StringReturns String
Free text about what the action does. The MCP server sends it to AI clients as the description of the tool; without summary it sends the name option.
NEWACTION('tasks_create', {
summary: 'Creates a task and returns its ID',
input: '*name:String',
action: function($, model) {
$.success(UID());
}
});
config
oninput: Function
since 0.0.19
Called right before the action.
oninput: FunctionReturns Function
function($). It runs after validation and middleware, so $.model, $.params and $.query are ready and you can change them.
NEWACTION('notes_create', {
input: '*body:String',
oninput: function($) {
$.model.body = $.model.body.trim();
},
action: function($, model) {
$.success();
}
});
config
mcp: Boolean
Makes the action a tool of the MCP server.
mcp: BooleanReturns Boolean
With true and the configuration key $mcp, AI clients can list and call the action at POST /$mcp/. The input, query and params schemas become the arguments of the tool. See MCP server.
NEWACTION('tasks_list', {
summary: 'Lists the tasks',
mcp: true,
action: function($) {
NOSQL('tasks').find().callback($);
}
});
config
onoutput: Function
since 0.0.19
Called after the action responds.
onoutput: FunctionReturns Function
function(err, response, $). It runs after a successful response has been delivered, so err is null; it is not called when the action fails.
NEWACTION('orders_create', {
input: '*productid:UID',
onoutput: function(err, response, $) {
console.log($.id, $.user ? $.user.id : '', response);
},
action: function($, model) {
$.success(UID());
}
});
property
$.model
The validated payload.
$.modelReturns Object
The payload after input validation, or the raw payload without input. $.payload and $.value are the same value; you can also assign it. It is also the second argument of action.
action: function($) {
var name = $.model.name;
$.success(name);
}
property
$.input
since 0.0.19
Another name of $.model.
$.inputReturns Object
Reads and assigns the same value as $.model.
oninput: function($) {
$.input.email = $.input.email.toLowerCase();
}
property
$.params
The URL parameters.
$.paramsReturns Object
Validated by the params option. In an HTTP request it contains the dynamic parts of the route; from code it is set with ACTION().params().
action: function($) {
DATA.read('products').id($.params.id).callback($);
}
property
$.query
The query string.
$.queryReturns Object
Validated by the query option. From code it is set with ACTION().query().
action: function($) {
var page = $.query.page || 1;
$.success(page);
}
property
$.user
The current user.
$.userReturns Object
The user of the HTTP request (see Authorization), or the user set with ACTION().user(). Empty for anonymous calls.
action: function($) {
$.success($.user.name);
}
property
$.config
The config option of the action.
$.configReturns Object
An empty object when the action has no config.
action: function($) {
$.success($.config.table);
}
property
$.id
The name of the running action.
$.idReturns String
In a chain of actions, the name of the current one.
action: function($) {
console.log('Running', $.id);
$.success();
}
property
$.controller
The controller of the HTTP request.
$.controllerReturns Controller
undefined when the action is called from code without a controller. $.client is the same; $.websocket is set when the controller is a WebSocket client.
action: function($) {
$.success($.controller ? $.controller.url : 'code');
}
property
$.error
The errors of the call.
$.errorReturns ErrorBuilder
An ErrorBuilder. $.invalid() adds to it; $.error.length is the number of errors.
action: function($) {
if (!$.model.items.length) {
$.invalid('No items', 'items');
return;
}
$.success();
}
property
$.response
The responses of the actions in a chain.
$.responseReturns Object
An object with the responses of the actions that already finished in the same call, by their names. The next action of the chain can use them.
NEWACTION('orders_notify', {
action: function($) {
var created = $.response.orders_create;
$.success(created);
}
});
property
$.xhr
since 0.0.19
Whether the request is an XHR request.
$.xhrReturns Boolean
true when the HTTP request has the X-Requested-With: XMLHttpRequest header; null without a controller.
action: function($) {
if ($.xhr)
$.success();
else
$.redirect('/');
}
property
$.meta
since 0.0.19
The definition of the action.
$.metaReturns Object
The object passed to NEWACTION(), with all its options.
action: function($) {
$.success($.meta.name);
}
property
$.env
The environment of the call.
$.envReturns Any
The value passed to ACTION().env(); undefined when it is not set. Use it to tell the action where it is called from, for example from a test or a job. $.action() does not pass it on: call .env($) on the inner call.
NEWACTION('orders_sync', {
action: function($) {
if ($.env === 'test') {
$.success();
return;
}
$.success('synced');
}
});
ACTION('orders_sync').env('test').callback(console.log);
property
$.ip
Request data shortcuts.
$.ipReturns String
$.ip, $.address, $.headers, $.url, $.uri, $.path, $.split, $.split2, $.files, $.body, $.mobile, $.ua, $.language and $.sessionid read the same properties of the controller. Without a controller they are empty (null, '' or an empty array).
action: function($) {
$.success({ ip: $.ip, ua: $.ua });
}
method
$.success([value])
Ends the action with a success object.
$.success([value])| Parameter | Type | Description |
|---|---|---|
value? |
Object |
A value for the value property |
Responds with { success: true, value: value } (the shape comes from DEF.onSuccess). Without a value, value is undefined.
action: function($) {
$.success(UID());
}
method
$.invalid(error, [path], [index])
Ends the action with an error.
$.invalid(error, [path], [index])| Parameter | Type | Description |
|---|---|---|
error |
String|Number|Error |
The error, or an HTTP status code |
path? |
String |
The field the error belongs to |
index? |
Number |
The index of the item in an array |
Returns ErrorBuilder The errors
Adds the error to $.error and fails the call. A number above 399 is an HTTP status (401, 404); a string is an error message. The caller's callback gets the ErrorBuilder, a route responds with the errors. Returns $.error.
action: function($) {
DATA.read('products').id($.params.id).callback(function(err, response) {
if (response)
$.callback(response);
else
$.invalid(404);
});
}
method
$.callback([value])
Ends the action with a value as it is.
$.callback([value])| Parameter | Type | Description |
|---|---|---|
value? |
Object |
The response |
Returns Function A callback when called without arguments
Responds with value without wrapping it. Without arguments, it returns a function(err, response) callback that adds err to the errors and responds with response. $.pipe is the same method. You can also pass $ itself to a database callback().
action: function($) {
$.callback({ count: 5 });
}
action: function($) {
DATA.find('products').callback($.callback());
}
method
$.done([value])
Returns a callback that ends the action.
$.done([value])| Parameter | Type | Description |
|---|---|---|
value? |
Object|Boolean |
The value of the success object, or true for the response |
Returns Function function(err, response)
Returns function(err, response). An error ends the action with the error; otherwise it calls $.success(value), or $.success(response) when value is true.
action: function($, model) {
model.id = UID();
DATA.insert('products', model).callback($.done(model.id));
}
method
$.promisify(fn, [a], [b], [c])
Calls a callback function as a Promise.
$.promisify(fn, [a], [b], [c])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
A function whose last argument is function(err, response) |
a? |
Object |
First argument |
b? |
Object |
Second argument |
c? |
Object |
Third argument |
Returns Promise The response
Calls fn(a, b, c, callback) and resolves with the response. An error ends the action with $.invalid() and the Promise never resolves.
action: async function($) {
var files = await $.promisify(F.Fs.readdir, PATH.public());
$.success(files);
}
method
$.action(name, [payload])
Runs another action from an action.
$.action(name, [payload])| Parameter | Type | Description |
|---|---|---|
name |
String |
Action name or names |
payload? |
Object |
The payload |
Returns ActionCaller The caller
Same as ACTION() with the controller of this action. Without a controller, the new call gets the user, query and params of this one.
action: async function($, model) {
var response = await $.action('stock_check', model).promise($);
$.success(response);
}
method
$.transform(name, value, [callback])
Runs a transformation with the controller of the action.
$.transform(name, value, [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the transformation |
value |
Object |
The value |
callback? |
Function |
function(err, value) |
Returns Promise A Promise without a callback
Same as TRANSFORM(), with the controller (and its user) of the action. Without a callback it returns a Promise.
action: async function($) {
var user = await DATA.read('users').id($.params.id).promise($);
$.callback(await $.transform('user', user));
}
method
$.unauthorized(permission, [permission2], [...])
Checks permissions of the user.
$.unauthorized(permission, [permission2], [...])| Parameter | Type | Description |
|---|---|---|
permission |
String |
A permission name; more can follow |
Returns Boolean true when the user is not allowed
Returns false when $.user has at least one of the permissions (in permissions or roles) or is sa/su. Otherwise it calls $.invalid(401) and returns true, so you only return.
action: function($) {
if ($.unauthorized('reports'))
return;
$.success();
}
method
$.redirect(url)
Redirects the HTTP request.
$.redirect(url)| Parameter | Type | Description |
|---|---|---|
url |
String |
The target URL |
Redirects the controller to url and cancels the action; the caller gets no response.
action: function($) {
$.redirect('/login/');
}
method
$.invalidsafe(message, [error])
Ends the action with a message and logs the real error.
$.invalidsafe(message, [error])| Parameter | Type | Description |
|---|---|---|
message |
String|Number |
The error for the caller, or an HTTP status code |
error? |
Error|String |
The error for the log |
Returns ErrorBuilder The errors
Adds message to $.error and fails the call, like $.invalid(message). error is written to the error log with F.error() (the name of the action and the URL are added) and is not sent to the caller. Use it when the error has details that the client must not see. Returns $.error.
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);
}
}
});
method
ACTION(name).callback(fn)
Receives the result of the call.
ACTION(name).callback(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function|Options |
function(err, response) or a $ |
Returns ActionCaller The caller, for chaining
fn(err, response); err is an ErrorBuilder or null, When you pass the $ of another action, errors go to its $.invalid() and the response to its $.callback(). .pipe() is the same method.
ACTION('products_list').callback(function(err, response) {
console.log(err ? err.toString() : response);
});
action: function($) {
ACTION('products_list').user($).callback($);
}
method
$.throw(error)
Writes an error to the log.
$.throw(error)| Parameter | Type | Description |
|---|---|---|
error |
Error|String |
The error |
Returns Options The same $
Passes error to the error handler of the framework (DEF.onError) with the name of the action and the URL: it is printed, kept in F.errors and emitted as the error event. The action goes on; to end it, call $.invalid(). Returns $.
NEWACTION('orders_notify', {
action: function($) {
NOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {
err && $.throw(err);
});
$.success();
}
});
method
$.touch([url])
Clears the cached state of a static file.
$.touch([url])| Parameter | Type | Description |
|---|---|---|
url? |
String |
The URL of the file Default: $.url |
Returns Options The same $
Calls TOUCH(url). Without url it uses the URL of the request; without a controller (an action called from code) every static file is cleared. Use it after the action changes a file in public/. Returns $.
NEWACTION('theme_save', {
input: '*css:String',
action: async function($, model) {
await F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css);
$.touch('/css/theme.css');
$.success();
}
});
method
ACTION(name).promise([$])
Returns a Promise with the result.
ACTION(name).promise([$])| Parameter | Type | Description |
|---|---|---|
$? |
Options |
The $ of an action that receives the errors |
Returns Promise The response
Resolves with the response. On error it rejects with an Error whose message contains the errors; with $, the error goes to $.invalid() instead and the Promise does not resolve.
var response = await ACTION('products_list').promise();
method
ACTION(name).user(user)
Sets the user of the call.
ACTION(name).user(user)| Parameter | Type | Description |
|---|---|---|
user |
Object|Options |
A user object, or a $ |
Returns ActionCaller The caller, for chaining
Sets $.user. When you pass a $, its user is used.
ACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);
method
ACTION(name).query(obj)
Sets the query string of the call.
ACTION(name).query(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The query |
Returns ActionCaller The caller, for chaining
Sets the object validated by the query option.
ACTION('products_list').query({ page: 2 }).callback(console.log);
method
ACTION(name).params(obj)
Sets the URL parameters of the call.
ACTION(name).params(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The parameters |
Returns ActionCaller The caller, for chaining
Sets the object validated by the params option.
ACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);
method
ACTION(name).ctrl(controller)
Runs the call with a controller.
ACTION(name).ctrl(controller)| Parameter | Type | Description |
|---|---|---|
controller |
Controller |
A controller |
Returns ActionCaller The caller, for chaining
The action gets $.controller and the request shortcuts. Accepts a controller or an object with a controller property (a $).
function handler($) {
ACTION('products_list').ctrl($).autorespond();
}
method
ACTION(name).autorespond()
Sends the result to the controller.
ACTION(name).autorespond()Returns ActionCaller The caller, for chaining
On error it calls controller.invalid(err); otherwise it responds with the controller in the format set by $.output() (JSON by default). Routes with --> use it. Needs a controller.
exports.install = function() {
ROUTE('GET /api/products/', function($) {
$.action('products_list').autorespond();
});
};
method
ACTION(name).status(fn)
Receives status messages from the action.
ACTION(name).status(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(a, b, c, d) |
Returns ActionCaller The caller, for chaining
The action sends them with $.status(a, b, c, d); the arguments go to fn. Without this method, $.status() does nothing.
NEWACTION('import_run', {
action: function($) {
$.status('started');
$.success();
}
});
ACTION('import_run').status(console.log).callback(console.log);
method
ACTION(name).progress(fn)
since 0.0.16
Receives progress messages from the action.
ACTION(name).progress(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(a, b, c, d) |
Returns ActionCaller The caller, for chaining
The action sends them with $.progress(a, b, c, d); the arguments go to fn with $ as this. Without this method, $.progress() does nothing.
NEWACTION('import_run', {
action: function($) {
for (var i = 1; i <= 10; i++)
$.progress(i * 10);
$.success();
}
});
ACTION('import_run').progress(p => console.log(p + '%')).callback(console.log);
method
ACTION(name).config(obj)
since 0.0.17
Adds configuration for this call.
ACTION(name).config(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
Keys for $.config |
Returns ActionCaller The caller, for chaining
The keys of obj are merged into a copy of the action's config, so $.config holds both; the definition of the action is not changed.
NEWACTION('report_build', {
config: { format: 'pdf' },
action: function($) {
$.success($.config);
}
});
ACTION('report_build').config({ lang: 'en' }).callback(console.log);
// { success: true, value: { format: 'pdf', lang: 'en' } }
method
ACTION(name).env(value)
Sets the environment of the call.
ACTION(name).env(value)| Parameter | Type | Description |
|---|---|---|
value |
Any|Options |
The environment, such as 'test', or a $ |
Returns ActionCaller The caller, for chaining
Sets $.env in the action. When you pass a $, its env is used, so an inner call can keep the environment of the outer one.
ACTION('orders_sync').env('test').callback(console.log);
NEWACTION('orders_close', {
action: async function($) {
await $.action('orders_sync').env($).promise($);
$.success();
}
});
method
SUCCESS([value])
Creates the success object that actions and controllers respond with.
SUCCESS([value])| Parameter | Type | Description |
|---|---|---|
value? |
Object |
A value for the value property |
Returns Object { success: true, value: value }
Returns { success: true, value: value }. The shape comes from DEF.onSuccess, the same function $.success() uses, so a custom DEF.onSuccess changes both. Use it when you build a response yourself, for example in a controller or in a callback.
ROUTE('POST /api/ping/', function($) {
$.json(SUCCESS(NOW));
});