Spanish Total.js
English
Documentation For AI agents
Contents

APIs

NEWAPI(), API() and its methods, TotalAPI() and their configuration keys.

.md GitHub
On this page

The functions and configuration keys of named APIs, including the Total.js API service. The guide APIs explains how they work together with examples; this page is the exact reference.

API

method

NEWAPI(name, [config], callback)

Registers the code that calls one API service.
ParameterTypeDescription
name String The name, or names separated by commas.
config? Object Default settings copied into opt.config.
callback Function function(opt, next); next(err, response) ends the call.

Registers the handler of an API service. this in the handler is the API call. A name is found in the spelling given to NEWAPI() or in lower case; several names separated by commas share one handler. The name * handles every name without its own handler. A function alone, or a config object and a function, registers the name default. The optional config holds default settings: before each call its keys are copied into opt.config, unless the call already set them with .configure(). Pass null as the callback to remove a handler. F.newapi() is the same function.

Register a service
NEWAPI('Weather', { region: 'eu' }, function(opt, next) {
	REQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {
		next(err, response && response.body.parseJSON());
	}});
});
type

function(opt, next)

The options a NEWAPI() handler receives.

The first argument of a NEWAPI() handler. It holds opt.name (the lower-case name of the service), opt.schema (the operation), opt.data, opt.controller (the $ of the call), opt.output (set by .output()), opt.files (an array of { name, filename, path } added by .file()), opt.retries (how many times the call was retried), opt.config (the config of NEWAPI() merged with .configure()) and opt.api (the API call). opt.retry() runs the handler again on the next tick and increases opt.retries.

Retry
NEWAPI('Weather', function(opt, next) {
	callservice(opt.schema, opt.data, function(err, response) {
		if (err && opt.retries < 3)
			opt.retry();
		else
			next(err, response);
	});
});
method

API(name, schema, data, [$])

Calls a service registered with NEWAPI().
ParameterTypeDescription
name String The name of the service.
schema String The operation, passed as opt.schema.
data Object The payload, passed as opt.data.
$? Object The $ of an action or a controller.

Returns APICall The call with the methods below.

Creates the call and runs the handler on the next tick, so you configure the call with its methods right away. $ becomes opt.controller. When no handler matches (and no * handler exists), the call fails with API is not initialized. F.api() is the same function.

Inside an action
NEWACTION('weather_read', {
	input: '*city:String',
	action: function($, model) {
		API('Weather', 'current', model).callback($);
	}
});
method

API().callback(fn)

Sets the callback of the call.
ParameterTypeDescription
fn Function|Object A callback, or $.

Returns APICall

fn is function(err, response), or the $ of an action, whose $.callback() receives the result. .pipe() is an alias.

Callback
API('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {
	console.log(err, response);
});
method

API().promise([$])

Returns a promise of the call.
ParameterTypeDescription
$? Object The $ of an action.

Returns Promise

The promise resolves with the response. On an error it rejects with an Error; when $ is given, the error goes to $.invalid() instead.

Await
var weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);
method

API().data(fn)

Runs a function with the response of a successful call.
ParameterTypeDescription
fn Function function(response).

Returns APICall

fn(response) runs before the callback.

Data
API('Weather', 'current', { city: 'Oslo' }).data(function(response) {
	MAIN.weather = response;
});
method

API().fail(fn)

Runs a function with the error of a failed call.
ParameterTypeDescription
fn Function function(err).

Returns APICall

fn(err) runs before the callback.

Fail
API('Weather', 'current', { city: 'Oslo' }).fail(function(err) {
	console.error(err);
});
method

API().error(message, [reverse])

Turns an empty response into an error.
ParameterTypeDescription
message String The error.
reverse? Boolean Fail on a non-empty response. Default: false

Returns APICall

When the handler answers without an error but the response is empty (a falsy value or an empty array), the call fails with message. With reverse, it fails when the response is truthy (an empty array too). .err() is an alias.

Not found
API('Weather', 'current', model).error('City not found').callback($);
method

API().output(type)

Sets the output format of the call.
ParameterTypeDescription
type String The format, e.g. json, base64, stream.

Returns APICall

The value is stored in opt.output for the handler. See TotalAPI() for the formats of the TAPI service.

Base64
API('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);
method

API().file(filename, path, [name])

Adds a file to the call.
ParameterTypeDescription
filename String The name of the file.
path String The path of the file on the disk.
name? String The field name. Default: file + index

Returns APICall

The file is added to opt.files as { name, filename, path }. The default name is file0, file1, ...

Upload
API('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);
method

API().controller($)

Sets the controller of the call.
ParameterTypeDescription
$ Object The $ of an action or a controller.

Returns APICall

Stores $.controller (or $ itself when it has none) in opt.controller.

Controller
API('Weather', 'current', model).controller($).callback($);
method

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

Writes an audit log after a successful call.
ParameterTypeDescription
$ Object The $ of an action.
message String The message.
type? String The type of the log.

Returns APICall

Calls $.audit(message, type) once the call succeeds. Placeholders in the message such as {data.id} are filled from the data of the call, and {user.name} from the user of $.

Audit
API('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);
method

API().debug()

Prints the result of the call to the console.

Returns APICall

Prints the name, the operation, the error and the response.

Debug
API('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);
method

API().configure(obj)

since 0.0.16 Sets configuration keys of the call.
ParameterTypeDescription
obj Object The keys to set.

Returns APICall

Copies the keys of obj into opt.config. They override the config given to NEWAPI(). The TAPI service reads token from it.

Another token
API('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);
method

TotalAPI(schema, data, [callback])

Calls an operation of Total.js API.
ParameterTypeDescription
schema String The operation, e.g. check.
data Object The payload.
callback? Function function(err, response).

Returns APICall Configure it like any API() call.

The same as API('TAPI', schema, data). The TAPI (or TotalAPI) service sends a POST request to https://<$tapiurl>.api.totaljs.com/<schema>/ with the token from .configure({ token }), CONF.totalapi, CONF.secret_totalapi or CONF.$tapisecret and the app name. When $tapi is false, every operation except check fails with totalapi_inactive. A non-object data is sent as { value: data }. With .output() the response is json (default), html, plain, text, buffer, binary, base64, stream, or #storage [id] [filename], which saves it into that FileStorage. A response with a status above 200 fails with the error from Total API.

Check the token
TotalAPI('check', {}, function(err, response) {
	console.log(err, response);
});
Save into FileStorage
// operation: a Total API operation that returns a file
API('TAPI', operation, data).output('#files').callback(console.log);
config

totalapi : token

The token of Total.js API.

Returns String

A string longer than five characters is stored as CONF.secret_totalapi and sent by the TAPI service. Any other value (true, false) is stored as $tapi.

Config
// /config
totalapi       : your-totalapi-token
config

$tapi : true

Allows calls of the TAPI service.

Returns Boolean

Default true. When false, every TAPI operation except check fails with totalapi_inactive.

config

$tapiurl : eu

The region of Total.js API.

Returns String

Default eu. Requests go to https://<$tapiurl>.api.totaljs.com/.

Made in Europe