Controller
The $ object of a route action: request data, uploaded files, responses, errors, headers and cookies.
On this page
In Total.js 5 the action of a route receives one argument, the controller, written as $ by convention. The controller holds everything about the HTTP request and has the methods that send the response. A new controller is created for each request.
exports.install = function() {
ROUTE('GET /products/{id}/', detail);
};
function detail($) {
$.json({ id: $.params.id, ip: $.ip });
}The routes themselves are described in Routing. The full list of properties and methods is in the reference of Controller.
Request data
| Property | What it contains |
|---|---|
$.method | The HTTP method in upper case (GET, POST...) |
$.url | The path of the URL, with a trailing slash and without the query string |
$.split | The segments of the path as an array (/a/b/ gives ['a', 'b']) |
$.params | The dynamic parts of the URL ({id}) as strings |
$.query | The query string as an object (?page=2 gives { page: '2' }) |
$.body | The parsed body: JSON, a URL-encoded form or the fields of a multipart form |
$.files | Uploaded files of a multipart/form-data request |
$.payload | The raw body as a Buffer (not for multipart requests) |
$.headers | The request headers, with lower-case names |
$.ip | The IP address of the client (the first X-Forwarded-For address behind a proxy) |
$.ua | A short name of the system and the browser, parsed from User-Agent |
$.mobile, $.robot | true for mobile devices, or for crawlers |
$.xhr | true when the request has X-Requested-With: XMLHttpRequest |
$.user | The user returned by your authorization delegate, or undefined |
$.language | The language returned by your localization delegate, or an empty string |
$.protocol, $.host, $.address | http or https, the Host header and the full URL |
$.req, $.res | The Node.js request and response objects |
exports.install = function() {
ROUTE('POST /api/contact/', contact);
};
function contact($) {
var model = $.body;
var page = $.query.page;
var agent = $.headers['user-agent'];
$.success();
}Values of $.params, $.query and URL-encoded forms are strings: convert numbers and dates yourself, or use an action with a schema (see Actions and JSON schemas). The body is read only for POST, PUT, PATCH and DELETE requests. A body bigger than the size limit of the route is refused with 431.
Uploaded files
The fields of a multipart/form-data request are in $.body and the files in $.files. Each file has name (the field), filename, type, size, extension, width and height for images, and methods to move(), read(), copy() or save the file into a file storage with fs(). Uploaded files are temporary: they are removed when the response ends, unless you moved them.
exports.install = function() {
ROUTE('POST /upload/ <5MB', upload);
};
function upload($) {
var file = $.files[0];
if (!file || !file.isImage) {
$.invalid('@(Upload an image)');
return;
}
file.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) {
if (err)
$.invalid(err);
else
$.success();
});
}The flag <5MB raises the size limit of the body for this route (the default is the configuration key $httpmaxsize, 256 kB). See Routing.
Sending a response
Each method below ends the request. Call only one of them per request.
| Method | Response |
|---|---|
$.json(value) | JSON |
$.success([value]) | { success: true, value: value } as JSON |
$.invalid(error) | An error as JSON, with status 400 or the status of the error |
$.jsonstring(text) | A string that is already JSON |
$.html(text), $.plain(text), $.xml(text) | Text with the right content type |
$.view(name, [model]) | A rendered view |
$.file(path, [download]) | A file from the disk |
$.stream(type, stream, [download]) | A readable stream |
$.binary(buffer, type, [download]) | A Buffer |
$.content(value, [type]) | A string or a Buffer with your content type |
$.redirect(url, [permanent]) | A redirect with 302, or 301 |
$.empty() | Status 204 without a body |
$.fallback(code, [error]) | An error page (or JSON for XHR requests) |
exports.install = function() {
ROUTE('GET /api/products/', list);
ROUTE('GET /download/', download);
ROUTE('GET /old/', function($) {
$.redirect('/new/', true);
});
};
function list($) {
NOSQL('products').find().callback(function(err, response) {
if (err)
$.invalid(err);
else
$.json(response);
});
}
function download($) {
$.file(PATH.root('reports/2025.pdf'), 'report.pdf');
}$.json(value, [beautify], [replacer]) serializes value with JSON.stringify(), sets content-type: application/json and headers that disable caching (cache-control: private, no-cache, no-store, max-age=0, expires: -1). Pass true as beautify to indent the output with tabs, and a replacer function (or an array of keys) to filter the values, exactly as the second argument of JSON.stringify().
ROUTE('GET /api/debug/', function($) {
$.json({ id: 1, password: 'secret' }, true, function(key, value) {
return key === 'password' ? undefined : value;
});
});$.callback() without arguments returns a function (err, value) that answers with $.invalid(err) or $.json(value), which is handy for callbacks of the database: NOSQL('products').find().callback($.callback()). $.done([value]) does the same and wraps the value with { success: true, value: ... }.
Errors
$.invalid() accepts a string, an Error, an ErrorBuilder or an HTTP status code. The response is a JSON array of errors. Text written as @(text) is translated with the resources of the request language.
function update($) {
if (!$.body.name) {
$.invalid('Name is required');
return;
}
if (!$.user) {
$.invalid(401);
return;
}
$.success($.body.name);
}$.invalidsafe(message, error) sends message like $.invalid() and writes error to the error log, so the client does not see the details of the error. $.throw(error) only writes an error to the log; you still send a response.
function report($) {
F.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {
if (err)
$.invalidsafe('The report is not available', err);
else
$.content(buffer, 'text/csv');
});
}$.fallback(code) sends the built-in error page with the given status. When you define a route like ROUTE('#404', fn), that action handles the request instead; the status is 200 unless the action sets $.response.status. For XHR requests the error is sent as JSON.
Status and headers
The response that will be sent is in $.response. Change $.response.status and $.response.headers before you call a response method:
function create($) {
$.response.status = 201;
$.response.headers['x-version'] = '1';
$.json({ id: UID() });
}For HTTP caching, $.httpcache(date) sets Last-Modified, Expires and Cache-Control, and $.notmodified(date) answers with 304 when the browser already has the same version.
Cookies
$.cookie(name) reads a cookie and $.cookie(name, value, expires, [options]) sets one. expires is a Date or a string such as '7 days'. The options are domain, path (default /), secure, httponly and samesite ('Lax', 'Strict', 'None'). The defaults for secure and samesite come from the configuration keys $cookiesecure and $cookiesamesite.
function login($) {
$.cookie('session', 'abc123', '7 days', { httponly: true });
$.success();
}
function profile($) {
var session = $.cookie('session');
$.json({ session: session });
}To remove a cookie, set it with an empty value and a date in the past.
Views
$.view(name, [model]) renders a file from the /views/ directory and sends it as HTML. $.layout(name) chooses the layout for the next view. See Views.
function homepage($) {
$.layout('layout');
$.view('index', { title: 'Home' });
}Other helpers
$.action(name, model)runs an action with this controller (see Actions).$.authorize([callback])runs your authorization delegate manually and fills$.user.$.proxy(url)forwards the request to another server and sends its answer.$.hostname([path])returnsprotocol://hostwith an optional path.$.href([key], [value])returns the query string of the request with one parameter changed, for paging and sorting links;$.href({ page: 1, sort: 'price' })returns the URL with several parameters changed.$.touch([url])clears the cached state of a static file after you change it (see Static files).$.csrf()creates a CSRF token.$.custom()tells the framework that you write to$.resyourself.