Message Service and APIs
TMS functions, the TMS client, API(), NEWAPI(), TotalAPI() and API routes.
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.
NEWPUBLISH(name, [schema])| Parameter | Type | Description |
|---|---|---|
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.
NEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');
NEWPUBLISH('orders_created');
method
PUBLISH(name, data)
since 0.0.42
Sends a message to TMS clients subscribed to the channel.
PUBLISH(name, data)| Parameter | Type | Description |
|---|---|---|
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.
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.
NEWSUBSCRIBE(name, [schema], [callback])| Parameter | Type | Description |
|---|---|---|
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).
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.
SUBSCRIBE(name, callback)| Parameter | Type | Description |
|---|---|---|
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.
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.
UNSUBSCRIBE(name, [callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
NEWCALL(name, schema, [callback])| Parameter | Type | Description |
|---|---|---|
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.
NEWCALL('products_detail', '*id:UID', function(data, next, client) {
NOSQL('products').one().where('id', data.id).callback(next, 404);
});
NEWCALL('orders_create', '*Orders --> create');
type
{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }
The JSON messages exchanged on the TMS endpoint.
{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }Returns Object
Every message is a JSON object with type:
meta(server to client):name,publish,subscribeandcall(arrays of{ id, schema }) andsubscribers(channels the app subscribes to). Sent after connecting and one second after any change.publish(server to client):{ id, data }, sent byPUBLISH().subscribe(client to server):{ id, data }, a message for aNEWSUBSCRIBE()channel.subscribers(client to server):{ subscribers: [names] }, the channels the client wants to receive.call(both ways):{ id, data, callbackid }; the answer addssuccess: trueorerror: true.ping: answered withpong.
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.
{ "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.
secret_tms : tokenReturns 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.
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.
default_tms_maxlength : 1024Returns Number
Applied to the WebSocket route of the TMS endpoint (default_tms_url). Default: 1024 (1 MB).
default_tms_maxlength : 5120
property
publish: true | String
since 0.0.72
Option of schema.action() and NEWACTION() that declares a TMS publish channel.
publish: true | StringReturns 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().
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.
$.publish(value)| Parameter | Type | Description |
|---|---|---|
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.
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.
TMSCLIENT(url, [token], [callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
client.subscribe(name, callback)| Parameter | Type | Description |
|---|---|---|
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.
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.
client.publish(name, data)| Parameter | Type | Description |
|---|---|---|
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.
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().
client.call(name, data, [callback], [timeout])| Parameter | Type | Description |
|---|---|---|
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.
client.call('products_detail', { id: '1a2b3c' }, function(err, response) {
console.log(err, response);
});
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.
client.readyReturns Boolean
It becomes false when the connection closes and true again after the next meta.
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.
client.metaReturns Object
It contains the server name and the publish, subscribe and call lists with JSON schemas. See TMS messages.
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.
client.on('meta', function(meta) {})| Parameter | Type | Description |
|---|---|---|
meta |
Object |
The meta message |
The server sends the meta after connecting, after reconnecting and after any change of its channels or calls.
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.
client.on('ready', function() {})Use it to run code after every reconnection; the TMSCLIENT() callback runs only the first time.
client.on('ready', function() {
console.log('TMS ready');
});
method
NEWAPI(name, [callback])
since 0.0.65
Registers an API provider used by API().
NEWAPI(name, [callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
API(name, schema, [data], [$])| Parameter | Type | Description |
|---|---|---|
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.
API('TotalAPI', 'check').callback(function(err, response) {
console.log(err, response);
});
action: function($, model) {
API('Payments', 'charge', model).callback($);
}
method
api.callback(fn)
Sets the callback of the API call.
api.callback(fn)| Parameter | Type | Description |
|---|---|---|
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.
API('TotalAPI', 'check').callback($);
method
api.promise([$])
Returns a promise with the response.
api.promise([$])| Parameter | Type | Description |
|---|---|---|
$? |
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).
var response = await API('TotalAPI', 'check').promise($);
method
api.output(type)
Sets the output format of the response.
api.output(type)| Parameter | Type | Description |
|---|---|---|
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.
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.
api.file(filename, path, [name])| Parameter | Type | Description |
|---|---|---|
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.
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.
api.error(err, [reverse])| Parameter | Type | Description |
|---|---|---|
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().
API('Payments', 'detail', { id: id }).error('404').callback($);
method
api.fail(fn)
Runs a function when the call fails.
api.fail(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(err) |
Returns APICall The call, for chaining
fn(err) runs in addition to the callback.
API('Payments', 'charge', model).fail(console.error).data(console.log);
method
api.data(fn)
Runs a function with the response when the call succeeds.
api.data(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(response) |
Returns APICall The call, for chaining
fn(response) runs in addition to the callback, only without an error.
API('TotalAPI', 'check').data(function(response) {
console.log(response);
});
method
api.audit($, [message], [type])
Writes an audit log entry when the call succeeds.
api.audit($, [message], [type])| Parameter | Type | Description |
|---|---|---|
$ |
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().
API('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);
method
api.controller($)
Passes a controller to the provider.
api.controller($)| Parameter | Type | Description |
|---|---|---|
$ |
Object |
A controller or $ |
Returns APICall The call, for chaining
Sets opt.controller to $.controller (or $ itself).
API('Payments', 'charge', model).controller($).callback($);
method
api.debug()
Logs the result of the call to the console.
api.debug()Returns APICall The call, for chaining
Prints the provider name, the schema, the error and the response.
API('TotalAPI', 'check').debug().callback(NOOP);
method
TotalAPI([token], type, data, [callback], [filename])
Sends one request to Total API.
TotalAPI([token], type, data, [callback], [filename])| Parameter | Type | Description |
|---|---|---|
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.
TotalAPI('check', {}, function(err, response) {
console.log(err, response);
});
var response = await TotalAPI('check', {});
config
totalapi : token
The Total API token.
totalapi : tokenReturns String
Used by TotalAPI(), the TotalAPI provider of API() and the audit logger. secret_totalapi is read when totalapi is empty.
totalapi : my-totalapi-token
config
default_tapi : eu
The Total API server region.
default_tapi : euReturns String
Requests go to https://{default_tapi}.api.totaljs.com/. Default: eu.
default_tapi : eu
config
allow_totalapilogger : false
since 0.0.42
Sends audit logs to Total API.
allow_totalapilogger : falseReturns 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.
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.
ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])| Parameter | Type | Description |
|---|---|---|
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.
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');
};
{ "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.
ROUTE('API /url/ name', 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.
exports.install = function() {
ROUTE('API /api/ -ping', function() {
this.success();
});
ROUTE('API /api/ +echo', function() {
this.json(this.body.data);
});
};