Spanish Total.js
English
Documentation For AI agents
Contents

Message Service and APIs

TMS functions, the TMS client, API(), NEWAPI(), TotalAPI() and API routes.

.md GitHub
On this page

TMS channels are declared with NEWPUBLISH(), NEWSUBSCRIBE() and NEWCALL(), and another app connects with TMSCLIENT(). API() calls providers registered with NEWAPI(). The guide Message Service and APIs explains how the parts work together; this page is the exact reference.

API

method

NEWPUBLISH(name, [schema])

since 0.0.42 Declares a TMS channel that your app publishes to.
ParameterTypeDescription
name String Name of the channel
schema? String|Object An inline declaration (id:UID, name:String), a JSON schema object with $id, or the name of a JSON schema or a Total.js schema. Leave it out to remove the channel

Returns undefined

The channel and its JSON schema are sent to every TMS client in the meta message. A schema name that does not exist throws an error. Without schema (or with null), the channel is removed. Redeclaring an existing channel keeps its first schema.

Declare a channel
NEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');
Remove a channel
NEWPUBLISH('orders_created');
method

PUBLISH(name, data)

since 0.0.42 Sends a message to TMS clients subscribed to the channel.
ParameterTypeDescription
name String Name of a channel declared with NEWPUBLISH()
data Object The message

Returns undefined

Only clients that announced a subscription to name receive the message. It does nothing when no TMS client is connected or when name was not declared with NEWPUBLISH(). The data is not validated on the server; TMSCLIENT() converts it with the channel schema.

Publish after an insert
NEWPUBLISH('orders_created', 'id:UID, total:Number');

function created(order) {
	PUBLISH('orders_created', { id: order.id, total: order.total });
}
method

NEWSUBSCRIBE(name, [schema], [callback])

since 0.0.42 Declares a TMS channel that clients publish to and your app receives.
ParameterTypeDescription
name String Name of the channel
schema? String|Object An inline declaration (id:UID, name:String), a JSON schema object with $id, or the name of a JSON schema or a Total.js schema. Leave it out to remove the channel
callback? Function A handler function(data, client)

Returns undefined

Incoming messages of the channel are validated with schema; invalid messages are dropped and valid ones go to the handlers added with SUBSCRIBE(). callback is a shortcut for SUBSCRIBE(name, callback). Without schema, the channel is removed (its handlers stay).

Declare a channel with a handler
NEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {
	NOSQL('products').modify({ price: data.price }).where('id', data.id);
});
method

SUBSCRIBE(name, callback)

since 0.0.42 Adds a handler for messages of a TMS subscribe channel.
ParameterTypeDescription
name String Name of the channel
callback Function function(data, client)

Returns undefined

The handler receives the validated data and the WebSocket client that sent it. A channel can have many handlers. Messages arrive only for channels declared with NEWSUBSCRIBE(). The app announces its subscriptions to the clients in the next meta message.

Add a handler
NEWSUBSCRIBE('products_updated', '*id:UID, price:Number');

SUBSCRIBE('products_updated', function(data, client) {
	console.log(client.ip, 'updated', data.id);
});
method

UNSUBSCRIBE(name, [callback])

since 0.0.42 Removes one handler or all handlers of a TMS channel.
ParameterTypeDescription
name String Name of the channel
callback? Function The handler to remove

Returns Boolean true when something was removed

With callback, only that handler is removed (pass the same function you gave to SUBSCRIBE()). Without it, all handlers of the channel are removed.

Remove a handler
function onupdate(data) {
	console.log(data);
}

SUBSCRIBE('products_updated', onupdate);
UNSUBSCRIBE('products_updated', onupdate);
method

NEWCALL(name, schema, [callback])

since 0.0.45 Registers a TMS remote call that clients can run.
ParameterTypeDescription
name String Name of the call
schema String|Object An inline declaration (id:UID, name:String), a JSON schema object with $id, or the name of a JSON schema or a Total.js schema, or *Schema --> action
callback? Function|String function(data, next, client) or an operation name

Returns undefined

The data of a call is validated with schema; a validation error goes back to the client. callback(data, next, client) answers with next(err, response). Instead of a function, callback can be the name of an operation. With no callback and a schema like *Orders --> create, the call runs that schema action. NEWCALL(name, null) removes the call. A call that does not exist answers with error 404.

A call with a function
NEWCALL('products_detail', '*id:UID', function(data, next, client) {
	NOSQL('products').one().where('id', data.id).callback(next, 404);
});
A call that runs a schema action
NEWCALL('orders_create', '*Orders --> create');
type

{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }

The JSON messages exchanged on the TMS endpoint.

Returns Object

Every message is a JSON object with type:

  • meta (server to client): name, publish, subscribe and call (arrays of { id, schema }) and subscribers (channels the app subscribes to). Sent after connecting and one second after any change.
  • publish (server to client): { id, data }, sent by PUBLISH().
  • subscribe (client to server): { id, data }, a message for a NEWSUBSCRIBE() channel.
  • subscribers (client to server): { subscribers: [names] }, the channels the client wants to receive.
  • call (both ways): { id, data, callbackid }; the answer adds success: true or error: true.
  • ping: answered with pong.

You need this only to write a TMS client without TMSCLIENT(). A new client starts with an empty list of subscriptions and receives publish messages only for the channels it lists in subscribers.

A client subscribes and calls
{ "type": "subscribers", "subscribers": ["orders_created"] }
{ "type": "call", "id": "products_detail", "data": { "id": "1a2b3c" }, "callbackid": "1" }
config

secret_tms : token

since 0.0.42 The token that TMS clients must send.

Returns String

Clients send it in the x-token header. A wrong token closes the connection with code 4001; more than five failed attempts from one IP address block it until the daily reset. Changing the token closes the TMS connections. The value can also be a number. Default: empty, every client is accepted.

Protect TMS
allow_tms  : true
secret_tms : my-secret-token
config

default_tms_maxlength : 1024

since 0.0.80 Maximum size of a TMS message in kB.

Returns Number

Applied to the WebSocket route of the TMS endpoint (default_tms_url). Default: 1024 (1 MB).

Allow bigger messages
default_tms_maxlength : 5120
property

publish: true | String

since 0.0.72 Option of schema.action() and NEWACTION() that declares a TMS publish channel.

Returns Boolean|String

The channel is named after the action: Schema.action for schema.action(), the action name for NEWACTION(). true uses the input (or output) of the action as the channel schema. A string is its own inline schema; a string that starts with + adds its fields to the input. Send messages with $.publish().

Publish from an action
NEWSCHEMA('Orders', function(schema) {
	schema.action('create', {
		input: '*email:Email, *total:Number',
		publish: '+id:UID',
		action: function($, model) {
			model.id = UID();
			$.publish(model);
			$.success(model.id);
		}
	});
});
method

$.publish(value)

since 0.0.72 Publishes a message to the TMS channel of the current action.
ParameterTypeDescription
value Object The message

Returns SchemaOptions The same $, for chaining

Works in actions declared with the publish option; the channel name is the action ID. Like PUBLISH(), it does nothing without a connected TMS client. The fields of value are copied to a new object.

Publish and answer
action: function($, model) {
	$.publish(model).success();
}
method

TMSCLIENT(url, [token], [callback])

since 0.0.45 Connects to the TMS endpoint of another Total.js app.
ParameterTypeDescription
url String URL of the TMS endpoint, for example https://app.example.com/$tms/
token? String The server secret_tms
callback? Function function(err, client, meta)

Returns WebSocketClient The TMS client

Returns a WebSocket client (see WebSockets) with the extra methods subscribe(), publish() and call(). An http URL is changed to ws and the client reconnects when the server goes down. token is sent in the x-token header. callback(err, client, meta) runs once, after the first meta message.

Connect
TMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {
	console.log('Connected to', meta.name);
});
method

client.subscribe(name, callback)

since 0.0.45 Receives messages of a publish channel of the server.
ParameterTypeDescription
name String Name of a channel declared with NEWPUBLISH() on the server
callback Function function(data)

Returns undefined

The data is converted with the channel schema from meta, and handlers run only for channels the server publishes. The client sends its list of subscriptions to the server shortly after each call and again after reconnecting.

Subscribe
client.subscribe('orders_created', function(data) {
	console.log(data.id, data.total);
});
method

client.publish(name, data)

since 0.0.45 Sends a message to a subscribe channel of the server.
ParameterTypeDescription
name String Name of a channel declared with NEWSUBSCRIBE() on the server
data Object The message

Returns undefined

The server validates it with the schema of its NEWSUBSCRIBE() channel. Nothing is sent while the client is not connected.

Publish
client.publish('products_updated', { id: '1a2b3c', price: 99 });
method

client.call(name, data, [callback], [timeout])

since 0.0.45 Runs a remote call registered on the server with NEWCALL().
ParameterTypeDescription
name String Name of the call
data Object Data of the call
callback? Function function(err, response)
timeout? Number Timeout in milliseconds Default: 10000

Returns Promise|undefined A promise when there is no callback

callback(err, response) receives the response; errors from the server arrive as an ErrorBuilder. Without a callback it returns a promise. Before the connection is ready, it fails with TMS is offline; without an answer in time, with 408: Timeout.

Call with a callback
client.call('products_detail', { id: '1a2b3c' }, function(err, response) {
	console.log(err, response);
});
Call with await
var product = await client.call('products_detail', { id: '1a2b3c' });
property

client.ready

since 0.0.45 true when the client is connected and has received the meta.

Returns Boolean

It becomes false when the connection closes and true again after the next meta.

Check the state
if (client.ready)
	client.publish('products_updated', { id: id, price: price });
property

client.meta

since 0.0.45 The last meta message received from the server.

Returns Object

It contains the server name and the publish, subscribe and call lists with JSON schemas. See TMS messages.

List the remote calls
console.log(client.meta.call.map(item => item.id));
event

client.on('meta', function(meta) {})

since 0.0.45 Emitted each time the server sends its meta.
ParameterTypeDescription
meta Object The meta message

The server sends the meta after connecting, after reconnecting and after any change of its channels or calls.

Watch changes
client.on('meta', function(meta) {
	console.log('Server publishes', meta.publish.length, 'channels');
});
event

client.on('ready', function() {})

since 0.0.45 Emitted after each meta message, when the client is ready.

Use it to run code after every reconnection; the TMSCLIENT() callback runs only the first time.

After every connection
client.on('ready', function() {
	console.log('TMS ready');
});
method

NEWAPI(name, [callback])

since 0.0.65 Registers an API provider used by API().
ParameterTypeDescription
name String Name of the provider, several separated by commas, or *
callback? Function function(opt, next). Leave it out to remove the provider

Returns undefined

callback(opt, next) runs for each API() call with this name, with the call object as this. opt has name, schema, data, controller, and files and output when set. Answer with next(err, response). name is not case-sensitive, can list several names separated by commas, and * registers a fallback for unknown names. A name without callback removes the provider. The provider TotalAPI (alias TAPI) is registered by default.

A custom provider
NEWAPI('Payments', function(opt, next) {
	RESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);
});
method

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

Sends a request to a registered API provider.
ParameterTypeDescription
name String Name of the provider, for example TotalAPI
schema String The endpoint or operation of the provider
data? Object Data of the request
$? Object A controller or $, passed to the provider as opt.controller

Returns APICall The call object

Returns a call object. The request starts on the next tick, so chain the options and the callback right away. Without a provider for name (and no * provider), the call fails with API is not initialized.

Total API
API('TotalAPI', 'check').callback(function(err, response) {
	console.log(err, response);
});
Inside an action
action: function($, model) {
	API('Payments', 'charge', model).callback($);
}
method

api.callback(fn)

Sets the callback of the API call.
ParameterTypeDescription
fn Function|Object function(err, response), or $

Returns APICall The call, for chaining

fn(err, response). Pass $ (or an object with callback) to answer an action with the result.

With $
API('TotalAPI', 'check').callback($);
method

api.promise([$])

Returns a promise with the response.
ParameterTypeDescription
$? Object An object with invalid(), such as $

Returns Promise The response

With $, an error is sent with $.invalid() and the promise never resolves; without it the promise is rejected with an error named API(name --> schema).

Await the response
var response = await API('TotalAPI', 'check').promise($);
method

api.output(type)

Sets the output format of the response.
ParameterTypeDescription
type String The output format

Returns APICall The call, for chaining

The provider reads it as opt.output. The TotalAPI provider supports json (default), html, text, plain, base64, buffer or binary, stream, and #name id filename to save the response to a FileStorage.

Save the response to FileStorage
API('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);
method

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

Adds a file to the request.
ParameterTypeDescription
filename String Name of the file
path String Path to the file on disk
name? String Name of the form field Default: 'file' + index

Returns APICall The call, for chaining

Adds { name, filename, path } to opt.files. The TotalAPI provider then sends the data and files as a multipart request.

Send a file
API('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);
method

api.error(err, [reverse])

Turns an empty response into an error.
ParameterTypeDescription
err String The error
reverse? Boolean Fail when the response is not empty Default: false

Returns APICall The call, for chaining

An empty response (or an empty array) becomes err. With reverse, a non-empty response becomes the error instead. Alias: api.err().

Require a response
API('Payments', 'detail', { id: id }).error('404').callback($);
method

api.fail(fn)

Runs a function when the call fails.
ParameterTypeDescription
fn Function function(err)

Returns APICall The call, for chaining

fn(err) runs in addition to the callback.

Log errors
API('Payments', 'charge', model).fail(console.error).data(console.log);
method

api.data(fn)

Runs a function with the response when the call succeeds.
ParameterTypeDescription
fn Function function(response)

Returns APICall The call, for chaining

fn(response) runs in addition to the callback, only without an error.

Use the response
API('TotalAPI', 'check').data(function(response) {
	console.log(response);
});
method

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

Writes an audit log entry when the call succeeds.
ParameterTypeDescription
$ Object The $ of an action or operation
message? String The audit message
type? String Type of the entry

Returns APICall The call, for chaining

Calls $.audit(message, type). Variables in the message are filled from the data of the call with $.variables().

Audit a payment
API('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);
method

api.controller($)

Passes a controller to the provider.
ParameterTypeDescription
$ Object A controller or $

Returns APICall The call, for chaining

Sets opt.controller to $.controller (or $ itself).

Pass the controller
API('Payments', 'charge', model).controller($).callback($);
method

api.debug()

Logs the result of the call to the console.

Returns APICall The call, for chaining

Prints the provider name, the schema, the error and the response.

Debug a call
API('TotalAPI', 'check').debug().callback(NOOP);
method

TotalAPI([token], type, data, [callback], [filename])

Sends one request to Total API.
ParameterTypeDescription
token? String Total API token Default: CONF.totalapi
type String The Total API service
data Object Data of the request
callback? Function|Controller function(err, response), or a controller to stream a file
filename? String File name of a streamed file

Returns Promise|undefined A promise when there is no callback

Posts data to https://{default_tapi}.api.totaljs.com/{type}/. The token defaults to totalapi (or secret_totalapi). A non-object data is sent as { value: data }. Without a callback it returns a promise. A binary response goes to the callback as a stream, or, when callback is a controller, is sent to the client with filename. With allow_totalapi: false, only check works; other calls fail with totalapi_inactive.

Check the token
TotalAPI('check', {}, function(err, response) {
	console.log(err, response);
});
Await
var response = await TotalAPI('check', {});
config

totalapi : token

The Total API token.

Returns String

Used by TotalAPI(), the TotalAPI provider of API() and the audit logger. secret_totalapi is read when totalapi is empty.

Set the token
totalapi : my-totalapi-token
config

default_tapi : eu

The Total API server region.

Returns String

Requests go to https://{default_tapi}.api.totaljs.com/. Default: eu.

Region
default_tapi : eu
config

allow_totalapilogger : false

since 0.0.42 Sends audit logs to Total API.

Returns Boolean

When true and a Total API token is set, audit entries are sent to the Total API logger service instead of DEF.onAudit(). Default: false.

Enable
totalapi             : my-totalapi-token
allow_totalapilogger : true
method

ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])

Declares an API route: one POST URL that runs actions by name.
ParameterTypeDescription
url String The route declaration
fn? Function A custom handler with the controller as this
flags? Array Route flags

Returns Object The route

The client posts { "schema": "name/param?query", "data": {} } to the URL. The sign before the name sets how the data is handled: + validates it like POST, # like PATCH (partial), - sends none like GET. URL parameters can have a type after : (uid, number, guid, date); the first becomes $.id. Without *Schema --> action, the route runs the action with the same name (--> name). +API requires a signed-in user and -API an anonymous one. Unknown names answer 404, invalid parameters 400.

API routes
exports.install = function() {
	ROUTE('+API /api/ -orders_list      *Orders --> list');
	ROUTE('+API /api/ +orders_create    *Orders --> create');
	ROUTE('+API /api/ -orders_read/{id} *Orders --> read');
};
A request
{ "schema": "orders_read/1a2b3c?fields=id,total" }
method

ROUTE('API /url/ name', function() {})

since 0.0.95 An API route action handled by your own function.

Instead of *Schema --> action, pass a function. It runs with the controller as this; this.params holds the URL parameters, this.body the posted { schema, data } and this.id the first parameter. Answer with any controller method.

A custom action
exports.install = function() {
	ROUTE('API /api/ -ping', function() {
		this.success();
	});
	ROUTE('API /api/ +echo', function() {
		this.json(this.body.data);
	});
};
Made in Europe