Spanish Total.js
English
Documentation For AI agents
Contents

Operations and tasks

Global functions and the $ object of operations and tasks, plus commands, extensions and PROMISIFY().

.md GitHub
On this page

Operations (NEWOPERATION(), OPERATION(), RUN()) and tasks (NEWTASK(), TASK()) hold business logic outside of routes. Both receive a $ object; this page lists its properties and methods, and also commands, extensions and PROMISIFY(). The guide Operations and tasks explains how to use them with examples; this page is the exact reference.

API

method

NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])

Registers an operation.
ParameterTypeDescription
name String Name of the operation.
fn Function($, value) The operation. null removes it.
repeat? Number How many times to run the operation again when it ends with an error.
stop? Boolean Stops a RUN() chain when this operation fails. Default: true
binderror? Boolean In a RUN() chain, stores the error output as the response of this operation. Default: false
filter? String Schema for the query string, used by $.filter.

The function receives $ and the value. It must end with $.callback(), $.success(), $.invalid() or another method that calls the callback. A boolean in place of repeat is read as stop, and a string in any optional position is read as filter. Calling NEWOPERATION(name, null) removes the operation. Put operations in the /operations/ directory.

An operation
NEWOPERATION('users_count', function($, value) {
	NOSQL('users').count().callback(function(err, count) {
		if (err)
			$.invalid(err);
		else
			$.callback(count);
	});
});
Repeat after an error
NEWOPERATION('ping', function($) {
	RESTBuilder.GET('https://example.com/ping').callback($.done());
}, 3);
method

OPERATION(name, [value], callback, [options], [controller])

Runs one operation.
ParameterTypeDescription
name String Name of the operation, or a URL of a remote operation.
value? Object Value for $.value. Default: {}
callback Function(err, response, options) Called when the operation ends.
options? Object Custom options, available as $.options.
controller? Controller Controller of the current request, or a $ object.

The callback receives err (an ErrorBuilder or null), the response and options. When value is a function, it is the callback and the value is an empty object. A controller or a $ object passed as options is used as the controller. A missing operation ends with the error Operation "name" not found.

The name can also be a URL with an optional expiration, for example 'https://example.com/op.js <5 minutes>' (once and asap are accepted too). The file is downloaded, compiled and cached until it expires. It can contain a NEWOPERATION() declaration or a module with exports.install, exports.make or exports.exec.

Call an operation
OPERATION('users_count', function(err, response) {
	console.log(err, response);
});
From a route
exports.install = function() {
	ROUTE('GET /api/users/count/', count);
};

function count() {
	var self = this;
	OPERATION('users_count', self.query, self.callback(), self);
}
method

RUN(names, [value], callback, [options], [controller], [response_name])

Runs several operations one after another.
ParameterTypeDescription
names String|Array Operation names, separated by commas.
value? Object Shared value for $.value. Default: {}
callback Function(err, response, $) Called when the chain ends.
options? Object Custom options, available as $.options.
controller? Controller Controller of the current request.
response_name? String Name of the operation whose response is returned alone.

names is a comma-separated string or an array. All operations share one $ and one $.value. The callback receives err, the response and the $ object. The response has one key per operation; with response_name it is only the response of that operation. When an operation fails and its stop option is true (the default), the chain stops. Names that do not exist are skipped. A string in place of options or controller is read as response_name.

Chain two operations
RUN('check, save', { email: 'peter@example.com' }, function(err, response) {
	// response.check, response.save
	console.log(err, response);
});
Return one response
function create() {
	var self = this;
	RUN('check, save', self.body, self.callback(), null, self, 'save');
}
method

EACHOPERATION(fn)

Calls a function for each registered operation.
ParameterTypeDescription
fn Function(name) Called with the name of each operation.

The function receives the name of each operation.

List operations
EACHOPERATION(function(name) {
	console.log(name);
});
property

$.value

The value passed to the operation.

Returns Object

$.model is the same value. In a RUN() chain, every operation shares this object, so changes are visible to the next operations.

Read the value
NEWOPERATION('greet', function($) {
	$.callback('Hello ' + $.value.name);
});
property

$.options

The options passed to OPERATION() or RUN().

Returns Object

An empty object when no options were passed. OPERATION() passes it again as the third argument of the callback.

Use options
NEWOPERATION('export', function($) {
	$.callback({ format: $.options.format || 'json' });
});

OPERATION('export', {}, console.log, { format: 'csv' });
property

$.name

Name of the running operation.

Returns String

In a RUN() chain it changes with each operation.

Log the name
NEWOPERATION('sync', function($) {
	console.log('Running', $.name);
	$.success();
});
property

$.error

The ErrorBuilder of the operation.

Returns ErrorBuilder

$.invalid() pushes errors here. In a RUN() chain, each operation gets a new ErrorBuilder.

Push several errors
NEWOPERATION('validate', function($) {
	!$.value.name && $.error.push('name');
	!$.value.email && $.error.push('email');
	$.callback();
});
property

$.controller

The controller passed to the operation, or undefined.

Returns Controller

$.client is the same value. Request properties of $ read from this controller.

Check for a controller
NEWOPERATION('whoami', function($) {
	if ($.controller)
		$.callback($.user);
	else
		$.invalid('401');
});
property

$.user

The user of the current request.

Returns Object

Read from the controller, or null without a controller. The other request properties work the same way: $.session, $.sessionid, $.language, $.ip, $.id, $.req, $.res, $.url, $.uri, $.path, $.split, $.params, $.query, $.body, $.files, $.headers, $.ua, $.mobile and $.test.

Use the user and the query
NEWOPERATION('my_orders', function($) {
	NOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);
});
property

$.filter

The query string converted by the filter schema of the operation.

Returns Object

The schema is the filter argument of NEWOPERATION(), for example 'page:Number,q:String'. Without a schema it returns the raw query. Without a controller it returns an empty object.

Typed query
NEWOPERATION('products', function($) {
	var filter = $.filter;
	$.callback({ page: filter.page, q: filter.q });
}, 'page:Number,q:String');
method

$.callback([value])

Ends the operation and returns a value.
ParameterTypeDescription
value? Object The response, or an error.

Returns $

An Error or an ErrorBuilder with errors is pushed to $.error. You can also call it as $.callback(err, value). When the operation has errors and repeat left, it runs again instead.

Return a value
NEWOPERATION('now', function($) {
	$.callback(NOW);
});
Pass it as a callback
NEWOPERATION('users', function($) {
	NOSQL('users').find().callback($.callback);
});
method

$.success([success], [value])

Ends the operation with a success object.
ParameterTypeDescription
success? Boolean The success flag. Default: true
value? Object A value added as value.

Returns $

Returns { success: true } to the callback. $.success(value) adds value. $.success(false) sets success to false. In a RUN() chain, empty keys are left out.

Return the new id
NEWOPERATION('contact_save', function($) {
	var id = UID();
	$.value.id = id;
	NOSQL('contacts').insert($.value).callback(function() {
		$.success(id);
	});
});
method

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

Ends the operation with an error.
ParameterTypeDescription
name? String|Error Error name, error message or Error.
error? String Error message.
path? String Path of the field.
index? Number Index of the item in an array.

Returns $|Function

The arguments go to $.error.push(). Without arguments it returns a function function(err) that you can pass as a callback.

Return an error
NEWOPERATION('login', function($) {
	if (!$.value.email) {
		$.invalid('email', 'Email is required');
		return;
	}
	$.success();
});
method

$.done([arg])

Returns a callback that ends the operation with a success object.
ParameterTypeDescription
arg? Boolean|Object true adds the response; another value is added as it is.

Returns Function(err, response)

The returned function function(err, response) pushes err and calls back, or calls back with { success: true }. With arg set to true, the response is added as value; any other arg is added instead of the response.

Return the inserted record
NEWOPERATION('save', function($) {
	NOSQL('contacts').insert($.value).callback($.done(true));
});
method

$.successful(callback)

Returns a callback that handles errors for you.
ParameterTypeDescription
callback Function(a, b, c) Called when there is no error.

Returns Function(err, a, b, c)

The returned function function(err, a, b, c) calls $.invalid(err) when there is an error, otherwise it calls callback(a, b, c) with $ as this.

Skip error checks
NEWOPERATION('count', function($) {
	NOSQL('users').count().callback($.successful(function(count) {
		$.callback({ count: count });
	}));
});
method

$.redirect(url)

Ends the operation with a redirect.
ParameterTypeDescription
url String Target URL.

Returns $

When the operation was called with controller.callback(), the controller redirects to url.

Redirect after logout
NEWOPERATION('logout', function($) {
	$.cookie('session', null);
	$.redirect('/');
});
method

$.noop([nocustomresponse])

Ends the operation without calling the callback.
ParameterTypeDescription
nocustomresponse? Boolean true does not call controller.custom(). Default: false

Returns $

Use it when the operation answers the request itself. By default it also calls controller.custom(), so the framework does not send another response; true skips that call.

Answer the request yourself
NEWOPERATION('ping', function($) {
	$.controller.plain('pong');
	$.noop(true);
});
method

$.cookie(name, [value], [expire], [options])

Reads or writes a cookie of the current request.
ParameterTypeDescription
name String Cookie name.
value? String New value, or null to remove it.
expire? String|Date Expiration, for example '1 day'.
options? Object Cookie options.

Returns String|$

With only name it returns the cookie value. null as value removes the cookie. Needs a controller.

Write a cookie
NEWOPERATION('remember', function($) {
	$.cookie('lang', $.value.lang, '1 year');
	$.success();
});
method

$.variables(str, [data])

Replaces {key} placeholders in a string.
ParameterTypeDescription
str String Text with placeholders.
data? Object Values for {data.key}.

Returns String

Supported keys start with user., data., model. or value., query. and params.. Unknown keys are kept. Single or double braces work. It exists on the $ of operations and tasks.

Build a message
NEWOPERATION('notify', function($) {
	var text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });
	$.callback(text);
});
method

$.audit([message], [type])

Writes an audit log entry for the operation.
ParameterTypeDescription
message? String Audit message.
type? String Type of the entry.

Returns $

Calls AUDIT($, message, type) with data from the user, the request and the value. It exists on the $ of operations and tasks.

Audit a change
NEWOPERATION('remove', function($) {
	$.audit('Removed product ' + $.value.id);
	$.success();
});
property

$.response

Results of the previous operations in a RUN() chain.

Returns Object

An object with one key per operation that has already ended. Only set inside RUN().

Use a previous result
NEWOPERATION('invoice', function($) {
	var order = $.response.order;
	$.callback({ total: order.value.price });
});
property

$.meta

Information about a RUN() chain.

Returns Object

$.meta.items is the list of names, $.meta.current the running operation, $.meta.prev the previous one and $.meta.index the index of the running operation. Only set inside RUN().

Check the previous operation
NEWOPERATION('save', function($) {
	if ($.meta.prev !== 'check') {
		$.invalid('check');
		return;
	}
	$.success();
});
property

$.repeated

How many times the running operation was repeated in a RUN() chain.

Returns Number

Starts at 0 for each operation and grows each time the repeat option runs it again. Only set inside RUN().

Give up early
NEWOPERATION('fetch', function($) {
	if ($.repeated > 1)
		console.log('Second retry');
	RESTBuilder.GET('https://example.com/data').callback($.callback);
}, 3);
method

NEWTASK(name, fn)

Declares a task with named steps.
ParameterTypeDescription
name String Name of the task.
fn Function(push) Declares the steps with push(step, fn($, value)). null removes the task.

fn receives push(step, fn). Each step receives $ and the value, and this is $. NEWTASK(name, null) removes the task. Put tasks in the /tasks/ directory.

A task with two steps
NEWTASK('signup', function(push) {

	push('check', function($, value) {
		if (!value.email) {
			$.invalid('email');
			return;
		}
		$.next('save');
	});

	push('save', function($, value) {
		NOSQL('users').insert(value).callback($.done());
	});

});
method

TASK(name, step, callback, [options], [value])

Creates a task and starts it at a step.
ParameterTypeDescription
name String Name of the task, or 'name/step'.
step String The first step.
callback Function(err, response) Called when the task ends.
options? Controller|Object Controller or $ object, or the value.
value? Object Value for $.value. Default: {}

Returns TaskBuilder The task, $.

name and step can be one string 'name/step'; then the arguments are TASK('name/step', callback, [options], [value]). A controller or the $ of a schema, operation or task as options shares its request and its errors; any other options is used as the value. The step starts on the next tick, so you can add steps with $.push() first. Without a step, start it with $.exec().

The name can also be a URL with an optional expiration, for example 'https://example.com/task.js <1 hour>'. The file is downloaded and cached until it expires.

Run a task
TASK('signup', 'check', function(err, response) {
	console.log(err, response);
}, { email: 'peter@example.com' });
From a schema action, with "name/step"
TASK('signup/check', $.callback, $, $.model);
method

$.next(step, [step2], [...])

Runs the next step of the task.
ParameterTypeDescription
step String Name of the step. More names are tried in order.

Returns $

Runs the first step in the list that exists, first in steps added with $.push() and then in the task declaration. When none exists, the task ends. Does nothing after the task ended.

Go to the next step
push('check', function($, value) {
	$.next(value.paid ? 'ship' : 'pay');
});
method

$.next2([step])

Returns a callback that goes to the next step.
ParameterTypeDescription
step? String Name of the next step.

Returns Function(err)

The returned function function(err) calls $.invalid(err) on an error, otherwise it runs step, or ends the task when step is empty.

Continue after a write
push('save', function($, value) {
	NOSQL('orders').insert(value).callback($.next2('notify'));
});
method

$.end([data])

Ends the task.
ParameterTypeDescription
data? Object The response. Default: $.value

Returns $

Calls the task callback with the errors (or null) and data, or $.value when data is empty.

End with the value
push('price', function($, value) {
	value.total = value.price * value.count;
	$.end();
});
method

$.end2([send_value])

Returns a callback that ends the task.
ParameterTypeDescription
send_value? Boolean true returns the data of the callback. Default: false

Returns Function(err, data)

The returned function function(err, data) calls $.invalid(err) on an error, otherwise it ends the task with data when send_value is true, or with $.value.

End with the result
push('load', function($, value) {
	NOSQL('orders').one().where('id', value.id).callback($.end2(true));
});
method

$.success([data])

Ends the task with a success object.
ParameterTypeDescription
data? Object A value added as value.

Returns $

Ends the task with { success: true }, plus value when data is set.

End with success
push('notify', function($, value) {
	MAIL(value.email, 'Order', '=?/mails/order', value);
	$.success(value.id);
});
method

$.done([send_value])

Returns a callback that ends the task with a success object.
ParameterTypeDescription
send_value? Boolean true adds the data of the callback as value. Default: false

Returns Function(err, data)

The returned function function(err, data) calls $.invalid(err) on an error, otherwise it ends the task with { success: true }, plus value: data when send_value is true.

Save and finish
push('save', function($, value) {
	NOSQL('orders').insert(value).callback($.done(true));
});
method

$.invalid(err, [msg])

Ends the task with an error.
ParameterTypeDescription
err String|Error Error name or Error.
msg? String Error message.

Returns $

Pushes the error to $.error and ends the task. Does nothing after the task ended.

Stop the task
push('check', function($, value) {
	if (!value.items.length)
		$.invalid('items', 'The order is empty');
	else
		$.next('save');
});
method

$.push(step, fn)

Adds a step to this task only.
ParameterTypeDescription
step String Name of the step.
fn Function($, value) The step.

Returns $

The step is used before a step of the same name in the task declaration. Call it on the task that TASK() returns, before the first step runs.

Override a step
var task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });
task.push('save', function($, value) {
	$.success();
});
method

$.exec(step, [callback])

Starts the task at a step.
ParameterTypeDescription
step String The first step.
callback? Function(err, response) Called when the task ends.

Returns $

Sets the callback when given and runs step. Use it with a task created by TASK(name) without a step.

Start later
var task = TASK('signup');
task.value = { email: 'peter@example.com' };
task.exec('check', console.log);
method

$.callback(fn)

Sets the callback of the task.
ParameterTypeDescription
fn Function(err, response) The callback.

Returns $

fn is called once when the task ends, with the errors (or null) and the response.

Set the callback
var task = TASK('signup');
task.callback(function(err, response) {
	console.log(err, response);
});
task.exec('check');
property

$.value

The value shared by all steps of the task.

Returns Object

$.model is the same value. Steps also receive it as the second argument. It is an empty object when no value was passed.

Change the value
push('price', function($) {
	$.value.price = 100;
	$.next('save');
});
property

$.current

Name of the running step.

Returns String

$.prev holds the previous step and $.name the name of the task. The request properties ($.user, $.query, $.params, $.body and others) read from the controller, like in operations.

Log the step
push('save', function($) {
	console.log($.name, $.prev, '->', $.current);
	$.success();
});
method

PROMISIFY(fn, [a], [b])

since 0.0.97 Wraps a function with a callback in a Promise.
ParameterTypeDescription
fn Function A function whose last argument is callback(err, response).
a? Object First argument for fn.
b? Object Second argument for fn.

Returns Promise

Calls fn with the given arguments and a callback function(err, response) as the last argument. The promise resolves with response or rejects with err. Empty arguments are not passed.

Await a callback
async function count() {
	var self = this;
	try {
		var response = await PROMISIFY(OPERATION, 'users_count');
		self.json(response);
	} catch (err) {
		self.invalid(err);
	}
}
Read a file
var body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');
method

NEWCOMMAND(name, fn)

Adds a handler for a command.
ParameterTypeDescription
name String Name of the command.
fn Function(a, b, c, d) The handler. null removes all handlers.

A command can have several handlers; each call adds one. NEWCOMMAND(name, null) removes all handlers of the command. Run it with CMD().

A command
NEWCOMMAND('clear_prices', function(category) {
	MAIN.prices && delete MAIN.prices[category];
});
method

CMD(name, [a], [b], [c], [d])

Runs all handlers of a command.
ParameterTypeDescription
name String Name of the command.
a? Object First argument.
b? Object Second argument.
c? Object Third argument.
d? Object Fourth argument.

Passes up to four arguments to each handler. Does nothing when the command has no handler. Built-in commands include clear_viewscache, clear_smtpcache and refresh_tms.

Run a command
CMD('clear_prices', 'books');
CMD('clear_viewscache');
method

CMD2(name, [a], [b], [c], [d])

Returns a function that runs a command.
ParameterTypeDescription
name String Name of the command.
a? Object First argument.
b? Object Second argument.
c? Object Third argument.
d? Object Fourth argument.

Returns Function

The returned function runs all handlers with the given arguments. When the command has no handler, it returns NOOP.

Run a command later
setTimeout(CMD2('clear_viewscache'), 5000);
method

NEWEXTENSION(code, [callback], [extend])

Installs an extension from source code or a URL.
ParameterTypeDescription
code String Source code, or a URL.
callback? Function(err, module) Called when the extension is installed.
extend? Function(module) Called with the module before it is installed.

code is JavaScript that sets exports, or a URL to download it from. Optional exports: id, name, install(next), make(), done() and uninstall(). Without id the id is a hash of name or the code. An extension with the same id is removed first. The code can also be HTML with a <script total> block and <file name="..."> blocks; exports.files then maps each file name to a temporary path. The added remove() method uninstalls the extension. Files in the /extensions/ directory are installed when the app starts.

Install from a string
var code = 'exports.name = \'Hello\';\nexports.make = function() {\n\tROUTE(\'GET /hello/\', function() { this.plain(\'Hello\'); });\n};';

NEWEXTENSION(code, function(err, module) {
	console.log(err, module.id);
});
Install from a URL
NEWEXTENSION('https://example.com/extension.js', function(err, module) {
	err && console.error(err);
});
method

WORKFLOW(declaration, [tasks])

Creates a small in-memory state machine: named steps that move to each other with $.next().
ParameterTypeDescription
declaration Function function($) that adds the steps.
tasks? Object Steps as { name: function($, value) }. Default: {}

Returns Object The workflow $.

WORKFLOW() returns a $ object and passes it to declaration($), where you add steps with $.push(name, fn). Each step is function($, value). It is a local helper, not a registered task: nothing is stored or named globally.

MemberWhat it does
$.push(name, fn)Adds the step fn($, value)
$.next(name, [value])Runs the step name with value; $.trigger() is an alias. An unknown name destroys the workflow
$.next2(name)Returns function(value) that runs $.next(name, value), for callbacks
$.invalid(err)Calls $.error(err, $) when you set it, then destroys the workflow
$.current, $.prevThe name of the current and of the previous step
$.tasksThe steps, as an object
$.clone()A new workflow with the same steps
$.destroy()Ends it; later calls of $.next() do nothing

declaration can be null when you pass the steps as tasks.

Steps in order
var flow = WORKFLOW(function($) {

	$.error = function(err) {
		console.log('Error:', err);
	};

	$.push('load', function($, id) {
		NOSQL('orders').one().where('id', id).callback(function(err, order) {
			if (order)
				$.next('send', order);
			else
				$.invalid('error-orders-404');
		});
	});

	$.push('send', function($, order) {
		MAIL(order.email, 'Your order', 'mails/order', order);
		$.destroy();
	});

});

flow.next('load', '123');
Made in Europe