---
title: Actions
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/actions/
updated: 2026-11-18T16:57:24.576Z
---

# Actions

> NEWACTION() options, the $ object, ACTION() callers, NEWSCHEMA() and transformations.

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](../../guides/actions/). Schemas for `input`, `output`, `params` and `query` are described in [JSON schemas](../../guides/json-schemas/).

## API

### NEWACTION(name, options)

Type: `method`

Declares an action.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the action, e.g. `products_create` |
| `options` | `Object` | yes |  | 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`.

Example: A complete action
```js
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));
	}
});
```

Example: Remove an action
```js
var action = NEWACTION('temp_test', { action: $ => $.success() });
action.remove();
```

### ACTION(name, [payload], [controller])

Type: `method`

Runs one or more actions from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Action name, or names separated by spaces; a `+` or `-` prefix says whether the action uses the payload |
| `payload` | `Object` | no |  | The data validated by the `input` option |
| `controller` | `Controller` | no |  | 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.

Example: Callback
```js
ACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {
	console.log(err, response);
});
```

Example: Several actions
```js
ACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {
	// response is the response of orders_notify
});
```

### EXEC(name, [payload], [controller])

Type: `method`

An alias of `ACTION()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Action name or names |
| `payload` | `Object` | no |  | The payload |
| `controller` | `Controller` | no |  | A controller |

Returns: `ActionCaller` The caller

The same function as `ACTION()`.

Example: Promise
```js
var response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();
```

### NEWSCHEMA(name, callback)

Type: `method`

Groups actions under a common name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the schema |
| `callback` | `Function|String` | yes |  | `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.

Example: Actions of a schema
```js
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);
```

Example: A JSON schema
```js
NEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');
```

### NEWTRANSFORM(name, fn, [id])

Type: `method`

Adds a function to a named transformation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the transformation |
| `fn` | `Function` | yes |  | `function($, value)` |
| `id` | `String` | no |  | 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`.

Example: Add and remove
```js
NEWTRANSFORM('user', function($, value) {
	delete value.password;
	$.next();
}, 'password');

NEWTRANSFORM('user', null, 'password');
```

### TRANSFORM(name, value, [callback], [controller])

Type: `method`

Runs a named transformation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the transformation |
| `value` | `Object` | yes |  | The value to transform |
| `callback` | `Function` | no |  | `function(err, value)` |
| `controller` | `Controller` | no |  | 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.

Example: Callback
```js
TRANSFORM('user', user, function(err, value) {
	console.log(value);
});
```

Example: Promise
```js
var value = await TRANSFORM('user', user);
```

Example: Errors of the Promise form
```js
try {
	var value = await TRANSFORM('user', user);
} catch (err) {
	console.log(err.toString()); // the errors of $.invalid()
}
```

### ON('@' + name, function($, response) {})

Type: `event`

Emitted after an action responds successfully.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Options` | yes |  | The `$` of the action |
| `response` | `Object` | yes |  | 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.

Example: Notification
```js
ON('@orders_create', function($, response) {
	console.log('New order', response.value, 'by', $.user.id);
});
```

### action: Function

Type: `config`

The logic of the action.

Returns: `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.

Example: Basic
```js
NEWACTION('ping', {
	action: function($) {
		$.success(NOW);
	}
});
```

### input: String|Object

Type: `config`

Schema of the payload.

Returns: `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](../../guides/json-schemas/).

Example: Inline schema
```js
NEWACTION('contact_send', {
	input: '*name:String, *email:Email, message:String',
	action: function($, model) {
		$.success();
	}
});
```

### output: String|Object

Type: `config`

Schema of the response.

Returns: `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.

Example: Hide fields
```js
NEWACTION('users_read', {
	params: '*id:UID',
	output: 'id:UID, name:String, email:Email',
	action: function($) {
		DATA.read('users').id($.params.id).callback($);
	}
});
```

### params: String|Object

Type: `config`

Schema of the URL parameters.

Returns: `String|Object`

Validates `$.params`, the dynamic parts of the route (`{id}`). Errors have the prefix `params.`.

Example: Parameter
```js
NEWACTION('products_remove', {
	params: '*id:UID',
	route: '+DELETE /api/products/{id}/',
	action: function($) {
		DATA.remove('products').id($.params.id).callback($.done());
	}
});
```

### query: String|Object

Type: `config`

Schema of the query string.

Returns: `String|Object`

Validates `$.query`. Errors have the prefix `query.`.

Example: Query
```js
NEWACTION('products_search', {
	query: '*q:String, page:Number',
	route: 'GET /api/products/search/',
	action: function($) {
		DATA.find('products').search('name', $.query.q).callback($);
	}
});
```

### user: Boolean

Type: `config`

Requires a signed-in or an anonymous user.

Returns: `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.

Example: Signed-in user
```js
NEWACTION('account_read', {
	user: true,
	action: function($) {
		$.success($.user);
	}
});
```

### permissions: String|Array

Type: `config`

Required permissions.

Returns: `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.

Example: Permissions
```js
NEWACTION('invoices_remove', {
	permissions: 'invoices_remove,admin',
	params: '*id:UID',
	action: function($) {
		DATA.remove('invoices').id($.params.id).callback($.done());
	}
});
```

### route: String

Type: `config`

A route that runs the action.

Returns: `String`

A route string as in [Routing](../../guides/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).

Example: Route
```js
NEWACTION('products_create', {
	input: '*name:String',
	route: '+POST /api/products/',
	action: function($, model) {
		$.success();
	}
});
```

Example: API endpoint
```js
NEWACTION('products_list', {
	route: '+API ?',
	action: function($) {
		DATA.find('products').callback($);
	}
});
```

### middleware: String

Type: `config`

Middleware to run before the action.

Returns: `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](../../guides/middleware/).

Example: Middleware
```js
NEWACTION('reports_build', {
	middleware: 'ratelimit',
	action: function($) {
		$.success();
	}
});
```

### partial: Boolean

Type: `config`

Validates the input partially.

Returns: `Boolean`

With `true`, `input` validates only the fields present in the payload and does not check required fields. Useful for `PATCH` updates.

Example: Patch
```js
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());
	}
});
```

### extend: String

Type: `config`

Adds the response to the payload.

Returns: `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.

Example: Extend
```js
NEWACTION('order_totals', {
	extend: 'totals',
	action: function($, model) {
		$.callback({ count: 3, price: 120 });
	}
});
// response: { ...payload, totals: { count: 3, price: 120 } }
```

### audit: Boolean|String

Type: `config`

Writes an audit record after success.

Returns: `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`).

Example: Audit message
```js
NEWACTION('products_create', {
	input: '*name:String',
	audit: '{{ $.user.name }} created {{ $.model.name }}',
	action: function($, model) {
		$.success();
	}
});
```

### config: Object

Type: `config`

Custom configuration of the action.

Returns: `Object`

Any object; it is available as `$.config` in the action, so one function can serve several actions.

Example: Shared logic
```js
function list($) {
	DATA.find($.config.table).callback($);
}

NEWACTION('products_list', { config: { table: 'products' }, action: list });
NEWACTION('orders_list', { config: { table: 'orders' }, action: list });
```

### timeout: Number

Type: `config` · Since: `0.0.16`

A time limit of the action.

Returns: `Number`

In milliseconds. When the action does not respond in time, it fails with the error `Timeout.`; a later response is ignored.

Example: Timeout
```js
NEWACTION('reports_export', {
	timeout: 10000,
	action: function($) {
		setTimeout(() => $.success(), 2000);
	}
});
```

### cache: true | { query, params, input, user, language, key, expire }

Type: `config`

Keeps the response of the action in the cache.

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.

Example: A list cached per page
```js
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|');
```

Example: One entry per user
```js
NEWACTION('Account|profile', {
	user: true,
	cache: { user: true, expire: '1 minute' },
	action: function($) {
		DATA.read('users').id($.user.id).callback($);
	}
});
```

### summary: String

Type: `config`

A description of the action.

Returns: `String`

Free text about what the action does. The [MCP server](../../guides/mcp-server/) sends it to AI clients as the description of the tool; without `summary` it sends the `name` option.

Example: Summary
```js
NEWACTION('tasks_create', {
	summary: 'Creates a task and returns its ID',
	input: '*name:String',
	action: function($, model) {
		$.success(UID());
	}
});
```

### oninput: Function

Type: `config` · Since: `0.0.19`

Called right before the action.

Returns: `Function`

`function($)`. It runs after validation and middleware, so `$.model`, `$.params` and `$.query` are ready and you can change them.

Example: Prepare data
```js
NEWACTION('notes_create', {
	input: '*body:String',
	oninput: function($) {
		$.model.body = $.model.body.trim();
	},
	action: function($, model) {
		$.success();
	}
});
```

### mcp: Boolean

Type: `config`

Makes the action a tool of the MCP server.

Returns: `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](../../guides/mcp-server/).

Example: A tool
```js
NEWACTION('tasks_list', {
	summary: 'Lists the tasks',
	mcp: true,
	action: function($) {
		NOSQL('tasks').find().callback($);
	}
});
```

### onoutput: Function

Type: `config` · Since: `0.0.19`

Called after the action responds.

Returns: `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.

Example: Log
```js
NEWACTION('orders_create', {
	input: '*productid:UID',
	onoutput: function(err, response, $) {
		console.log($.id, $.user ? $.user.id : '', response);
	},
	action: function($, model) {
		$.success(UID());
	}
});
```

### $.model

Type: `property`

The validated payload.

Returns: `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`.

Example: Model
```js
action: function($) {
	var name = $.model.name;
	$.success(name);
}
```

### $.input

Type: `property` · Since: `0.0.19`

Another name of `$.model`.

Returns: `Object`

Reads and assigns the same value as `$.model`.

Example: Input
```js
oninput: function($) {
	$.input.email = $.input.email.toLowerCase();
}
```

### $.params

Type: `property`

The URL parameters.

Returns: `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()`.

Example: Params
```js
action: function($) {
	DATA.read('products').id($.params.id).callback($);
}
```

### $.query

Type: `property`

The query string.

Returns: `Object`

Validated by the `query` option. From code it is set with `ACTION().query()`.

Example: Query
```js
action: function($) {
	var page = $.query.page || 1;
	$.success(page);
}
```

### $.user

Type: `property`

The current user.

Returns: `Object`

The user of the HTTP request (see [Authorization](../../guides/authorization/)), or the user set with `ACTION().user()`. Empty for anonymous calls.

Example: User
```js
action: function($) {
	$.success($.user.name);
}
```

### $.config

Type: `property`

The `config` option of the action.

Returns: `Object`

An empty object when the action has no `config`.

Example: Config
```js
action: function($) {
	$.success($.config.table);
}
```

### $.id

Type: `property`

The name of the running action.

Returns: `String`

In a chain of actions, the name of the current one.

Example: Name
```js
action: function($) {
	console.log('Running', $.id);
	$.success();
}
```

### $.controller

Type: `property`

The controller of the HTTP request.

Returns: `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.

Example: Controller
```js
action: function($) {
	$.success($.controller ? $.controller.url : 'code');
}
```

### $.error

Type: `property`

The errors of the call.

Returns: `ErrorBuilder`

An `ErrorBuilder`. `$.invalid()` adds to it; `$.error.length` is the number of errors.

Example: Errors
```js
action: function($) {
	if (!$.model.items.length) {
		$.invalid('No items', 'items');
		return;
	}
	$.success();
}
```

### $.response

Type: `property`

The responses of the actions in a chain.

Returns: `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.

Example: Previous response
```js
NEWACTION('orders_notify', {
	action: function($) {
		var created = $.response.orders_create;
		$.success(created);
	}
});
```

### $.xhr

Type: `property` · Since: `0.0.19`

Whether the request is an XHR request.

Returns: `Boolean`

`true` when the HTTP request has the `X-Requested-With: XMLHttpRequest` header; `null` without a controller.

Example: XHR
```js
action: function($) {
	if ($.xhr)
		$.success();
	else
		$.redirect('/');
}
```

### $.meta

Type: `property` · Since: `0.0.19`

The definition of the action.

Returns: `Object`

The object passed to `NEWACTION()`, with all its options.

Example: Meta
```js
action: function($) {
	$.success($.meta.name);
}
```

### $.env

Type: `property`

The environment of the call.

Returns: `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.

Example: Environment
```js
NEWACTION('orders_sync', {
	action: function($) {
		if ($.env === 'test') {
			$.success();
			return;
		}
		$.success('synced');
	}
});

ACTION('orders_sync').env('test').callback(console.log);
```

### $.ip

Type: `property`

Request data shortcuts.

Returns: `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).

Example: IP and agent
```js
action: function($) {
	$.success({ ip: $.ip, ua: $.ua });
}
```

### $.success([value])

Type: `method`

Ends the action with a success object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no |  | A value for the `value` property |

Responds with `{ success: true, value: value }` (the shape comes from `DEF.onSuccess`). Without a value, `value` is `undefined`.

Example: Success
```js
action: function($) {
	$.success(UID());
}
```

### $.invalid(error, [path], [index])

Type: `method`

Ends the action with an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `String|Number|Error` | yes |  | The error, or an HTTP status code |
| `path` | `String` | no |  | The field the error belongs to |
| `index` | `Number` | no |  | 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`.

Example: Not found
```js
action: function($) {
	DATA.read('products').id($.params.id).callback(function(err, response) {
		if (response)
			$.callback(response);
		else
			$.invalid(404);
	});
}
```

### $.callback([value])

Type: `method`

Ends the action with a value as it is.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no |  | 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()`.

Example: Value
```js
action: function($) {
	$.callback({ count: 5 });
}
```

Example: Callback of a query
```js
action: function($) {
	DATA.find('products').callback($.callback());
}
```

### $.done([value])

Type: `method`

Returns a callback that ends the action.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|Boolean` | no |  | 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`.

Example: Done
```js
action: function($, model) {
	model.id = UID();
	DATA.insert('products', model).callback($.done(model.id));
}
```

### $.promisify(fn, [a], [b], [c])

Type: `method`

Calls a callback function as a Promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | A function whose last argument is `function(err, response)` |
| `a` | `Object` | no |  | First argument |
| `b` | `Object` | no |  | Second argument |
| `c` | `Object` | no |  | 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.

Example: Promisify
```js
action: async function($) {
	var files = await $.promisify(F.Fs.readdir, PATH.public());
	$.success(files);
}
```

### $.action(name, [payload])

Type: `method`

Runs another action from an action.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Action name or names |
| `payload` | `Object` | no |  | 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.

Example: Nested action
```js
action: async function($, model) {
	var response = await $.action('stock_check', model).promise($);
	$.success(response);
}
```

### $.transform(name, value, [callback])

Type: `method`

Runs a transformation with the controller of the action.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the transformation |
| `value` | `Object` | yes |  | The value |
| `callback` | `Function` | no |  | `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.

Example: Transform
```js
action: async function($) {
	var user = await DATA.read('users').id($.params.id).promise($);
	$.callback(await $.transform('user', user));
}
```

### $.unauthorized(permission, [permission2], [...])

Type: `method`

Checks permissions of the user.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `permission` | `String` | yes |  | 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.

Example: Check
```js
action: function($) {
	if ($.unauthorized('reports'))
		return;
	$.success();
}
```

### $.redirect(url)

Type: `method`

Redirects the HTTP request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The target URL |

Redirects the controller to `url` and cancels the action; the caller gets no response.

Example: Redirect
```js
action: function($) {
	$.redirect('/login/');
}
```

### $.invalidsafe(message, [error])

Type: `method`

Ends the action with a message and logs the real error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String|Number` | yes |  | The error for the caller, or an HTTP status code |
| `error` | `Error|String` | no |  | 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`.

Example: Hide the details
```js
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);
		}
	}
});
```

### ACTION(name).callback(fn)

Type: `method`

Receives the result of the call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|Options` | yes |  | `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.

Example: Callback
```js
ACTION('products_list').callback(function(err, response) {
	console.log(err ? err.toString() : response);
});
```

Example: Pass to another action
```js
action: function($) {
	ACTION('products_list').user($).callback($);
}
```

### $.throw(error)

Type: `method`

Writes an error to the log.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `Error|String` | yes |  | 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 `$`.

Example: Log and continue
```js
NEWACTION('orders_notify', {
	action: function($) {
		NOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {
			err && $.throw(err);
		});
		$.success();
	}
});
```

### $.touch([url])

Type: `method`

Clears the cached state of a static file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no | `$.url` | The URL of the file |

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 `$`.

Example: After a change
```js
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();
	}
});
```

### ACTION(name).promise([$])

Type: `method`

Returns a Promise with the result.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Options` | no |  | 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.

Example: Await
```js
var response = await ACTION('products_list').promise();
```

### ACTION(name).user(user)

Type: `method`

Sets the user of the call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `user` | `Object|Options` | yes |  | A user object, or a `$` |

Returns: `ActionCaller` The caller, for chaining

Sets `$.user`. When you pass a `$`, its user is used.

Example: User
```js
ACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);
```

### ACTION(name).query(obj)

Type: `method`

Sets the query string of the call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The query |

Returns: `ActionCaller` The caller, for chaining

Sets the object validated by the `query` option.

Example: Query
```js
ACTION('products_list').query({ page: 2 }).callback(console.log);
```

### ACTION(name).params(obj)

Type: `method`

Sets the URL parameters of the call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The parameters |

Returns: `ActionCaller` The caller, for chaining

Sets the object validated by the `params` option.

Example: Params
```js
ACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);
```

### ACTION(name).ctrl(controller)

Type: `method`

Runs the call with a controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `controller` | `Controller` | yes |  | 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 `$`).

Example: Controller
```js
function handler($) {
	ACTION('products_list').ctrl($).autorespond();
}
```

### ACTION(name).autorespond()

Type: `method`

Sends the result to the controller.

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.

Example: Route handler
```js
exports.install = function() {
	ROUTE('GET /api/products/', function($) {
		$.action('products_list').autorespond();
	});
};
```

### ACTION(name).status(fn)

Type: `method`

Receives status messages from the action.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Status
```js
NEWACTION('import_run', {
	action: function($) {
		$.status('started');
		$.success();
	}
});

ACTION('import_run').status(console.log).callback(console.log);
```

### ACTION(name).progress(fn)

Type: `method` · Since: `0.0.16`

Receives progress messages from the action.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Progress
```js
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);
```

### ACTION(name).config(obj)

Type: `method` · Since: `0.0.17`

Adds configuration for this call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | 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.

Example: Config
```js
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' } }
```

### ACTION(name).env(value)

Type: `method`

Sets the environment of the call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Any|Options` | yes |  | 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.

Example: Environment
```js
ACTION('orders_sync').env('test').callback(console.log);
```

Example: Pass it on
```js
NEWACTION('orders_close', {
	action: async function($) {
		await $.action('orders_sync').env($).promise($);
		$.success();
	}
});
```

### SUCCESS([value])

Type: `method`

Creates the success object that actions and controllers respond with.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no |  | 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.

Example: A success response in a controller
```js
ROUTE('POST /api/ping/', function($) {
	$.json(SUCCESS(NOW));
});
```
