Route syntax of Total.js 5
ROUTE(definition, handler) declares a route. The definition is one text with these parts, in this order:
[+|-]METHOD /url/{param}/ [@flag ...] [#middleware ...] [<limit] [--> *Action ...]
| Part | Meaning |
|---|---|
METHOD | GET, POST, PUT, PATCH, DELETE, or SOCKET for a WebSocket and FILE for URLs with an extension: a URL such as /a.txt is never matched by a GET route. |
+ or - before the method | + accepts only requests that AUTH() approved, - only anonymous requests; any other request is answered with 401. Without a prefix the route is open. |
/url/ | The path. Write the end slash: routes are matched with it. |
{name} | A segment of the path that is read from $.params.name. |
* as the last segment | Matches any path below it. A route without * is more specific and wins. |
@flag | A condition for the request: @json, @xml, @xhr, @upload, @debug, @release, @mobile, @robot, @referer (or @referrer). |
#name | A middleware registered with MIDDLEWARE(name, fn). |
<limit | <10kb limits the size of the body, <30s the time of the request. |
--> *Action | Runs one or more actions with the input of the request and answers with the result. |
#404, #401... | A route whose definition is only # and a status code replaces the error page. |
A request is handled by the first matching route. A request that does not meet the flags of a route continues to the next route and ends with a 404 when none matches; a request that does not meet + or - gets a 401. A route without flags on the same URL always wins over a route with flags, so never put both on one URL.
AUTH(function($) {
if ($.headers['x-token'] === 'secret')
$.success({ id: '1' });
else
$.invalid();
});
MIDDLEWARE('stamp', function($, next) {
$.response.headers['x-stamp'] = 'yes';
next();
});
NEWACTION('Echo/one', { name: 'one', input: '*text:String', action: ($, model) => $.callback({ one: model.text }) });
NEWACTION('Echo/two', { name: 'two', action: ($, model) => $.callback({ two: true }) });exports.install = function() {
ROUTE('GET /plain/', plain);
ROUTE('GET /users/{id}/', user);
ROUTE('GET /files/*', files);
ROUTE('POST /json/ @json', json);
ROUTE('+GET /private/', plain);
ROUTE('-GET /guest/', plain);
ROUTE('GET /stamped/ #stamp', plain);
ROUTE('POST /echo/ @json --> *Echo/one');
ROUTE('FILE /robots-example.txt', file);
ROUTE('#404', missing);
};
function plain($) {
$.json({ ok: true });
}
function user($) {
$.json({ id: $.params.id });
}
function files($) {
$.json({ url: $.url });
}
function json($) {
$.json({ body: $.body });
}
function file($) {
$.plain('from a FILE route');
}
function missing($) {
$.response.status = 404;
$.plain('custom 404');
}