Message Service and APIs
Publish, receive and call over the Total.js Message Service, connect with TMSCLIENT(), call APIs with API() and NEWAPI(), and expose API routes.
On this page
Total.js 4 has two ways to connect your app with other services:
- the Total.js Message Service (TMS), a WebSocket endpoint where your app publishes messages, receives messages and answers remote calls, all described by JSON schemas;
- APIs, a small layer that sends named requests to an API provider you register with
NEWAPI()(Total API is registered by default).
The same app can also expose its own API routes, one URL that runs many actions chosen by name.
Turning TMS on
TMS is off by default. Enable it in /config:
allow_tms : true
secret_tms : my-secret-tokenThe endpoint is default_tms_url (/$tms/); default_tms_maxlength sets the maximum size of a message in kB (default 1024). With secret_tms, a client must send the token in the x-token header. A wrong token closes the connection with code 4001, and an IP address with more than five failed attempts is refused until the daily reset. Without secret_tms, every client is accepted. See Configuration for the other options.
Publishing messages
A publish channel tells the clients which messages your app sends and how they look. Declare it with NEWPUBLISH(name, schema) and send messages with PUBLISH(name, data):
// definitions/tms.js
NEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');
NEWSCHEMA('Orders', function(schema) {
schema.action('create', {
input: '*email:Email, *total:Number',
action: function($, model) {
model.id = UID();
NOSQL('orders').insert(model);
PUBLISH('orders_created', model);
$.success(model.id);
}
});
});The schema can be an inline declaration ('id:UID, total:Number'), a JSON schema object with an $id, or the name of a JSON schema or a Total.js schema. A name that does not exist throws an error.
PUBLISH() sends the message only to connected clients that subscribed to the channel. With no TMS client connected, or for a channel not declared with NEWPUBLISH(), it does nothing. The data is not validated on the server: the client converts it with the schema from the channel.
Receiving messages
A subscribe channel is the other direction: clients send messages and your app handles them. NEWSUBSCRIBE(name, schema, [callback]) declares the channel and SUBSCRIBE(name, callback) adds handlers:
NEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {
NOSQL('products').modify({ price: data.price }).where('id', data.id);
});
// another handler for the same channel
SUBSCRIBE('products_updated', function(data) {
console.log('Product updated', data.id);
});Every incoming message is validated with the channel's schema; invalid messages are dropped. A handler receives the validated data and the WebSocket client. UNSUBSCRIBE(name, [callback]) removes one handler, or all of them.
Remote calls
NEWCALL(name, schema, callback) registers a call that clients run like a remote procedure. The data is validated first; the callback answers with next(err, response):
NEWCALL('products_detail', '*id:UID', function(data, next, client) {
NOSQL('products').one().where('id', data.id).callback(next, 404);
});
// or run a schema operation
NEWCALL('orders_create', '*Orders --> create');Automatic synchronization
When you add or remove channels, calls or handlers, the app sends a fresh meta message to all clients one second later. The meta lists the app name, the publish, subscribe and call channels with their JSON schemas, and the channels your app subscribes to.
Publishing from actions
schema.action() and NEWACTION() accept a publish option. It declares a publish channel named after the action (Schema.action, or the action name), and $.publish(value) in the action sends to it:
NEWACTION('Orders/create', {
input: '*email:Email, *total:Number',
publish: true,
action: function($, model) {
model.id = UID();
$.publish(model);
$.success(model.id);
}
});publish: true uses the action's input (or output) as the channel schema. A string sets its own schema; a string that starts with + adds fields to the input.
Connecting to TMS: TMSCLIENT()
TMSCLIENT(url, [token], [callback]) connects your app to the TMS endpoint of another Total.js app. It reconnects after the server restarts, and it resubscribes automatically:
TMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {
client.subscribe('orders_created', function(data) {
console.log('New order', data.id, data.total);
});
client.publish('products_updated', { id: '1a2b3c', price: 99 });
client.call('products_detail', { id: '1a2b3c' }, function(err, response) {
console.log(err, response);
});
});client.subscribe() receives messages of the server's publish channels, converted by their schema. client.publish() sends to the server's subscribe channels. client.call() runs a remote call; without a callback it returns a promise, and it fails with TMS is offline before the connection is ready or 408: Timeout after 10 seconds.
APIs: NEWAPI() and API()
API(name, schema, [data]) sends a request to a registered API provider and returns a call object. You chain options and a callback; the request starts on the next tick:
API('TotalAPI', 'check').callback(function(err, response) {
console.log(err, response);
});
// service_name is a placeholder for a Total API service
var base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise();NEWAPI(name, callback) registers your own provider. The callback receives opt (name, schema, data, controller, files, output) and next(err, response). The name * registers a fallback for every unknown name:
NEWAPI('Payments', function(opt, next) {
RESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);
});
API('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log);Names are not case-sensitive. The built-in provider TotalAPI (alias TAPI) posts to Total API with the token from totalapi; the older TotalAPI(type, data, callback) function does the same in one call.
API routes
An API route is one POST URL that runs many actions. The client sends { "schema": "name/param?query", "data": { ... } }:
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');
ROUTE('+API /api/ -ping', function() {
this.success();
});
};The sign before the name sets the HTTP method used for the action: + validates the data like POST, # like PATCH, - sends no data like GET. URL parameters follow the name. A function instead of *Schema --> action handles the call with the controller as this. The whole route syntax is in Routing.