Spanish Total.js
English
Documentation For AI agents
Contents

Controllers

The controller is this in every route action: it holds the request data and answers the request.

.md GitHub
On this page

Every action of a route runs with a controller as this. The controller holds the data of the request and has the methods that answer it. A new controller is created for each request.

exports.install = function() {
    ROUTE('GET /products/{id}/', detail);
};

function detail(id) {
    // id === this.params.id
    this.json({ id: id, ip: this.ip });
}

The dynamic parts of the URL arrive as arguments of the action, in their order. The full list of properties and methods is in the reference of Controller.

Request data

PropertyWhat it contains
this.bodyThe parsed body of the request (JSON or a form)
this.queryThe query string as an object (?page=2 gives { page: '2' })
this.paramsThe dynamic parameters of the URL, converted by their type ({page:number})
this.filesUploaded files, for routes with the upload flag
this.userThe user that your AUTH() delegate accepted, or undefined
this.headersThe request headers, with lower-case names
this.ipThe IP address of the client (the first X-Forwarded-For address behind a proxy)
this.urlThe path of the URL in lower case, with a trailing slash
this.uriThe parsed URL (pathname, query, hostname…)
this.uaA short name of the browser and the system, parsed from User-Agent
this.mobile, this.robottrue for mobile devices, or for crawlers
this.xhrtrue when the request has X-Requested-With: XMLHttpRequest
this.referrerThe Referer header, or an empty string
this.languageThe language set by your localization delegate
this.req, this.resThe request and the response objects of the framework
exports.install = function() {
    ROUTE('POST /api/contact/', contact);
};

function contact() {
    var model = this.body;
    var page = this.query.page;
    var agent = this.headers['user-agent'];
    this.success();
}

this.query and this.body contain strings: convert numbers and dates yourself, or let a schema do it (see Routing).

Uploaded files

A route with the upload flag reads multipart/form-data. Each item of this.files has name (the field), filename, type, size, extension, and width and height for images. move(), copy() and read() return a promise when you do not pass a callback:

exports.install = function() {
    ROUTE('POST /upload/', upload, ['upload'], 1024 * 5);
};

async function upload() {
    var file = this.files[0];
    if (!file || !file.isImage()) {
        this.invalid('Send an image');
        return;
    }
    await file.move(PATH.public('photos/' + file.filename));
    this.success();
}

The framework removes the temporary files when the request ends. Call this.autoclear(false) to keep them.

Answering

Answer each request once. The methods return the controller, so you can call return this.json(...) to stop the action.

MethodAnswer
this.json(obj)JSON (application/json)
this.plain(text)Plain text; an object is serialized as formatted JSON
this.html(body)HTML
this.content(body, type)Any text with your content type
this.view(name, [model])A rendered view from views/
this.file(filename, [download])A file from public/ (or any path that starts with ~)
this.binary(buffer, type)A buffer
this.stream(stream, type)A readable stream
this.redirect(url, [permanent])A redirect, 302 or 301
this.empty()An empty body
this.nocontent()204 No Content
this.success([value]){ "success": true }
this.invalid(error)An error as JSON, 400 by default
function download() {
    this.file('invoices/2024.pdf', 'invoice.pdf');
}

function legacy() {
    this.redirect('/new-address/', true);
}

The status code

Set this.status before you answer. json(), plain(), content(), html(), jsonstring() and empty() use it; the default is 200.

function create() {
    var item = { id: UID(), name: this.body.name };
    this.status = 201;
    this.json(item);
}

this.empty(204) sets the status and answers in one call.

Success and validation errors

this.success() answers { "success": true }. With a value it answers { "success": true, "value": ... }, and this.success(false) answers { "success": false }.

this.invalid() answers an array of errors as JSON with the status 400. A number as the first argument sets another status:

function save() {
    if (!this.body.email) {
        this.invalid('email', 'The email is required');
        return;
    }
    this.success(true, { id: UID() });
}

Two helpers create callbacks in the style (err, response). this.done() answers invalid(err) on error and success() otherwise; this.done(true) adds the response as value. this.callback() answers the response as JSON, or with a view when you pass its name:

function list() {
    // loadproducts(callback) is your own function
    loadproducts(this.callback());
}

function remove() {
    removeproduct(this.params.id, this.done());
}

Error pages

this.throw404() and its siblings answer with an error page: throw400(), throw401(), throw403(), throw404(), throw409(), throw500(), throw501() and throw503(). They have aliases named view400()… view503(). The argument is a description of the problem; throw500(err) also logs the error.

function detail(id) {
    var self = this;
    // findproduct(id, callback) is your own function
    findproduct(id, function(err, item) {
        if (item)
            self.view('detail', item);
        else
            self.throw404();
    });
}

To render your own page, declare a route for the status. The problem is in this.exception:

exports.install = function() {
    ROUTE('#404', notfound);
};

function notfound() {
    this.status = 404;
    this.view('404');
}

Without such a route the framework renders its own error page.

Headers and cache

this.header(name, value) sets a header of the response. Most answering methods also take an object with headers. this.nocache() disables the HTTP cache of the answer:

function report() {
    this.nocache();
    this.header('X-Report', 'daily');
    this.plain('...');
}

Cookies

this.cookie(name) reads a cookie. this.cookie(name, value, expires, [options]) writes it; expires is a text such as '5 days', and options are domain, path (/), secure, httponly and samesite (Lax by default):

function login() {
    this.cookie('session', 'token', '7 days', { httponly: true });
    this.redirect('/');
}

function logout() {
    this.cookie('session', '', '-1 day');
    this.redirect('/');
}

Views and layouts

this.view(name, [model]) renders views/name.html inside the layout views/layout.html. Routes of controllers/default.js find their views in views/; routes of another controller, for example controllers/admin.js, in views/admin/. A name that starts with ~ always starts in views/.

function home() {
    this.layout('layout_home');
    this.title('Welcome');
    this.view('index', { products: [] });
}
  • this.layout(name) chooses another layout; this.layout('') renders the view without a layout.
  • this.title() and this.meta(title, [description], [keywords], [image]) set values the layout prints with @{title} and @{meta}.
  • this.repository is an object shared by the view and its layout.
  • this.view(name, model, true) returns the HTML as a string instead of answering.

The template syntax is explained in Views.

Signed-in users

this.user is what your AUTH() delegate accepted. Routes with + run only for signed-in users, so this.user always exists there:

// definitions/auth.js
AUTH(function($) {
    var token = $.cookie('session');
    if (token === 'token')
        $.success({ id: 1, name: 'Peter' });
    else
        $.invalid();
});

// controllers/default.js
exports.install = function() {
    ROUTE('+GET /account/', account);
};

function account() {
    this.json(this.user);
}

Errors in actions

An exception thrown in an action is logged and the request gets the error page 500. In callbacks and promises nothing catches the exception for you: catch it and call this.throw500(err) or this.invalid(err).

async function stats() {
    try {
        var data = await loadstats();
        this.json(data);
    } catch (err) {
        this.throw500(err);
    }
}
Made in Europe