Spanish Total.js
English
Documentation For AI agents
Contents

Controller

Properties and methods of the controller, the object that answers a request.

.md GitHub
On this page

The controller is this inside every action of a route. It holds the request data and the methods that answer the request. The guide Controllers explains how to use it with examples; this page is the exact reference.

API

property

controller.body

The parsed body of the request.

Returns Object

A JSON or URL-encoded body is parsed into an object. Values of a form are strings. A route with a schema replaces it with the validated model. You can also assign a new object.

Read the body
exports.install = function() {
	ROUTE('POST /api/contact/', contact);
};

function contact() {
	var email = this.body.email;
	this.success();
}
property

controller.query

The query string of the URL as an object.

Returns Object

Values are strings: ?page=2 gives { page: '2' }. The object is parsed the first time you read it.

Paging
function list() {
	var page = (this.query.page || '1').parseInt();
	this.json({ page: page });
}
property

controller.params

The dynamic parameters of the URL.

Returns Object

Each {name} of the route becomes a key. Parameters declared with a type are converted: {id:number} with parseInt(), {active:boolean} with parseBoolean() and {date:date} with parseDate(). The same values arrive as arguments of the action.

Typed parameter
exports.install = function() {
	ROUTE('GET /orders/{id:number}/', order);
};

function order(id) {
	// this.params.id is a number
	this.json({ id: this.params.id });
}
property

controller.files

The uploaded files.

Returns Array

Only routes with the upload flag receive files. Each file has name (the form field), filename, type, size, extension, width and height, and the methods move(path), copy(path), read(), isImage(), isVideo() and isAudio(). move(), copy() and read() return a promise without a callback. The temporary files are removed when the request ends, unless you call controller.autoclear(false).

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

async function upload() {
	var file = this.files[0];
	await file.move(PATH.public('uploads/' + file.filename));
	this.success();
}
property

controller.user

The signed-in user.

Returns Object

The object that your AUTH() delegate passed to $.success(user). It is undefined when nobody is signed in. You can assign it.

Profile
exports.install = function() {
	ROUTE('+GET /api/profile/', profile);
};

function profile() {
	this.json({ name: this.user.name });
}
property

controller.headers

The headers of the request.

Returns Object

Header names are in lower case.

Read a header
function api() {
	var token = this.headers['x-token'];
	this.plain(token ? 'ok' : 'missing');
}
property

controller.ip

The IP address of the client.

Returns String

Behind a proxy it is the first address of the X-Forwarded-For header; otherwise the address of the connection.

property

controller.url

The path of the request URL in lower case.

Returns String

It has no query string and always ends with /.

property

controller.mobile

true when the client is a mobile device.

Returns Boolean

It is tested on the User-Agent header. You can assign it.

property

controller.xhr

true when the request was sent by XMLHttpRequest.

Returns Boolean

It is true when the request has the header X-Requested-With: XMLHttpRequest.

property

controller.language

The language of the request.

Returns String

It is the value returned by your localization delegate (DEF.onLocale). Views and controller.mail() translate texts with it.

property

controller.status

The HTTP status code of the answer.

Returns Number

Set it before you answer. json(), jsonstring(), plain(), content() and html() use it, and 200 when it is not set. invalid() uses a status over 399 for the errors.

Created
function create() {
	this.status = 201;
	this.json({ id: UID() });
}
property

controller.repository

An object shared by the view and its layout.

Returns Object

Values you store here before view() are available in the view and in the layout as repository. The page title and meta tags are stored in it too.

Pass a value to the layout
function home() {
	this.repository.menu = 'home';
	this.view('index');
}
property

controller.exception

The problem of an error route.

Returns Error|String

In a route for an error status (ROUTE('#404', ...), ROUTE('#500', ...)) it contains the problem passed to throw404(), throw500() and the others.

property

controller.req

The request object of the framework.

Returns Request

It extends the Node.js request. The properties of the controller like body, query and ip read from it.

method

controller.json(obj, [headers], [beautify], [replacer])

Answers with an object serialized as JSON.
ParameterTypeDescription
obj Object The value to serialize.
headers? Object Extra response headers.
beautify? Boolean Formats the JSON with indentation. Default: false
replacer? Function A replacer for JSON.stringify().

Returns Controller The controller.

The content type is application/json and the status is controller.status or 200. An ErrorBuilder is answered as its errors with its own status. beautify can be the second argument.

An object
exports.install = function() {
	ROUTE('GET /api/products/', products);
};

function products() {
	this.json([{ id: 1, name: 'Book' }]);
}
Formatted
this.json({ name: 'Peter' }, true);
method

controller.jsonstring(str, [headers])

since 0.0.57 Answers with a text that is already JSON.
ParameterTypeDescription
str String The JSON text.
headers? Object Extra response headers.

Returns Controller The controller.

Use it when you have the JSON as a string, for example from a cache. The text is sent as it is, with the content type application/json.

From a cache
function list() {
	this.jsonstring('[{"id":1}]');
}
method

controller.plain(body, [headers])

Answers with plain text.
ParameterTypeDescription
body String|Object The text.
headers? Object Extra response headers.

Returns Controller The controller.

The content type is text/plain. An object is serialized as formatted JSON; null gives an empty body.

Text
function home() {
	this.plain('Hello world');
}
method

controller.html(body, [headers])

Answers with HTML.
ParameterTypeDescription
body String The HTML.
headers? Object Extra response headers.

Returns Controller The controller.

The same as content(body, 'text/html', headers).

HTML
function home() {
	this.html('<h1>Hello</h1>');
}
method

controller.content(body, type, [headers])

Answers with a text and your content type.
ParameterTypeDescription
body String The content.
type? String The content type. Default: text/plain
headers? Object Extra response headers.

Returns Controller The controller.

An ErrorBuilder as body is answered as JSON with its own status.

XML
function feed() {
	this.content('<rss></rss>', 'application/xml');
}
method

controller.view([name], [model], [headers], [partial])

Renders a view and answers with it.
ParameterTypeDescription
name? String The name of the view without .html.
model? Object The model, available in the view as model.
headers? Object Extra response headers.
partial? Boolean Returns the HTML as a string and does not answer. It can be the third argument. Default: false

Returns Controller|String The controller, or the HTML when partial is true.

The view is a file name.html in views/, rendered inside the layout (layout by default, see controller.layout()). Routes of a controller other than default look for views in views/<controller name>/. The first character of the name changes where the file is looked up:

PrefixWhere
~The root of views/
#plugin/viewThe views of a plugin
=theme/viewThe views of a theme
@A package

Without a name, the view is named after the last part of the URL (index for /). With partial set to true the method returns the rendered HTML instead of answering.

A page
exports.install = function() {
	ROUTE('GET /', home);
};

function home() {
	this.view('index', { title: 'Home' });
}
HTML as a string
var html = this.view('~mail/order', order, true);
method

controller.layout(name)

Chooses the layout for the next view.
ParameterTypeDescription
name String The name of the layout view, or an empty string.

Returns Controller The controller.

The default layout is layout (the default_layout config). An empty string renders the view without a layout.

Without a layout
function widget() {
	this.layout('');
	this.view('widget');
}
method

controller.title(value)

Sets the title of the page.
ParameterTypeDescription
value String The title.

Returns Controller The controller.

The layout prints it with @{title}. The text is HTML-encoded.

Title
this.title('Products');
this.view('products');
method

controller.meta(title, [description], [keywords], [image])

Sets the meta values of the page.
ParameterTypeDescription
title String The title.
description? String The description.
keywords? String|Array The keywords.
image? String The URL of an image.

Returns Controller The controller.

The layout prints them with @{meta}. keywords can be an array.

Meta tags
this.meta('Products', 'All our products', ['shop', 'books']);
this.view('products');
method

controller.file(filename, [download], [headers], [callback])

Answers with a file.
ParameterTypeDescription
filename String The file in public/, or ~ and an absolute path.
download? String|Boolean A name for the downloaded file; true uses the name of the file.
headers? Object Extra response headers.
callback? Function Runs when the file is sent.

Returns Controller The controller.

The file is read from public/. A name that starts with ~ is an absolute path.

Download
function invoice() {
	this.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');
}
method

controller.binary(buffer, type, [encoding], [download], [headers])

Answers with a buffer.
ParameterTypeDescription
buffer Buffer The data.
type String The content type.
encoding? String A conversion of the data.
download? String A name for the downloaded file.
headers? Object Extra response headers.

Returns Controller The controller.

encoding converts the buffer before it is sent (binary, utf8, ascii).

An image in memory
function pixel() {
	var buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');
	this.binary(buffer, 'image/gif');
}
method

controller.stream(stream, type, [download], [headers], [callback], [nocompress])

Answers with a readable stream.
ParameterTypeDescription
stream Stream A readable stream.
type String The content type.
download? String A name for the downloaded file.
headers? Object Extra response headers.
callback? Function Runs when the stream is sent.
nocompress? Boolean Disables the compression. Default: false

Returns Controller The controller.

The answer is compressed unless nocompress is true. The first two arguments can be swapped (type, stream).

A CSV file
function exportcsv() {
	var stream = Fs.createReadStream(PATH.databases('export.csv'));
	this.stream(stream, 'text/csv', 'export.csv');
}
method

controller.redirect(url, [permanent])

Redirects the client to another URL.
ParameterTypeDescription
url String The target URL.
permanent? Boolean Sends 301 Moved Permanently. Default: false

Returns Controller The controller.

The status is 302, or 301 when permanent is true.

After a form
function save() {
	this.redirect('/thanks/');
}
method

controller.empty([headers])

Answers with an empty body.
ParameterTypeDescription
headers? Object|Number Extra headers, or a status code.

Returns Controller The controller.

A number instead of the headers sets the status code. For 204 No Content use also controller.nocontent([headers]).

Accepted
this.empty(202);
method

controller.success([success], [value])

Answers with the JSON { "success": true }.
ParameterTypeDescription
success? Boolean The value of success. Default: true
value? Object A value added as value.

Returns Controller The controller.

success(value) answers { "success": true, "value": value }. success(false) answers { "success": false }.

With a value
function create() {
	var id = UID();
	this.success(true, id);
	// {"success":true,"value":"..."}
}
method

controller.invalid([status], [error])

Answers with an error as JSON.
ParameterTypeDescription
status? Number|String|Error|ErrorBuilder A status code, the name of the error or the error.
error? String The text of the error.

Returns ErrorBuilder The builder with the errors.

The errors are answered as a JSON array with the status 400 (the default_errorbuilder_status config). A number as the first argument sets the status; an Error or an ErrorBuilder is answered as it is. The answer is sent in the next tick, so you can still add errors to the returned builder.

Validation
function save() {
	if (!this.body.email)
		return this.invalid('email', 'The email is required');
	this.success();
}
Another status
this.invalid(409, 'The user exists');
method

controller.done([value])

Creates a callback that answers success or an error.
ParameterTypeDescription
value? Boolean|Object true adds the response as value; another value is added as value itself.

Returns Function A callback (err, response).

The callback has the form (err, response). On error it calls controller.invalid(err). Otherwise it answers { "success": true }; with done(true) the response is added as value, and with another value that value is added.

Any callback (err, response)
function remove(id) {
	// removeproduct(id, callback) is your own function
	removeproduct(id, this.done());
}

function create() {
	// answers { "success": true, "value": response }
	createproduct(this.body, this.done(true));
}
method

controller.callback([view])

Creates a callback that answers the response as JSON or with a view.
ParameterTypeDescription
view? String The name of a view.

Returns Function A callback (err, data).

The callback has the form (err, data). When err is an ErrorBuilder and you did not pass a view, its errors are answered as JSON. Any other error answers the error page 404, or 500 when the ErrorBuilder contains an Error. Without an error it answers data as JSON, or renders the view with data as the model.

JSON
function list() {
	// loadproducts(callback) is your own function
	loadproducts(this.callback());
}
A view
function list() {
	loadproducts(this.callback('products'));
}
method

controller.throw404([problem])

Answers with the error page 404 Not Found.
ParameterTypeDescription
problem? String A description of the problem, available in the error route as controller.exception.

Returns Controller The controller.

It runs the route #404 when you declared one; otherwise the framework renders its own error page. The same family answers other statuses: throw400(), throw401(), throw403(), throw409(), throw500(), throw501() and throw503(). Each one has an alias named view400() … view503(). Nothing happens when the request was already answered.

Missing record
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();
	});
}
Your own page
exports.install = function() {
	ROUTE('#404', notfound);
};

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

controller.throw403([problem])

Answers with the error page 403 Forbidden.
ParameterTypeDescription
problem? String A description of the problem, available in the error route as controller.exception.

Returns Controller The controller.

It runs the route #403 when you declared one. Alias: view403().

Only for admins
function admin() {
	if (!this.user.admin)
		return this.throw403();
	this.view('admin');
}
method

controller.throw500([error])

Logs an error and answers with the error page 500.
ParameterTypeDescription
error? Error|String The error.

Returns Controller The controller.

The error is logged by the framework (DEF.onError). Then the route #500 runs when you declared one. Alias: view500().

In a promise
async function stats() {
	try {
		this.json(await loadstats());
	} catch (err) {
		this.throw500(err);
	}
}
method

controller.cookie(name, [value], [expires], [options])

Reads a cookie of the request or writes a cookie to the response.
ParameterTypeDescription
name String The name of the cookie.
value? String The value to write.
expires? String When the cookie expires, for example '7 days'.
options? Object domain, path, secure, httponly, samesite.

Returns String|Controller The value when reading, the controller when writing.

With one argument it returns the value of the cookie, or an empty string. With a value it adds a Set-Cookie header. expires is a text such as '5 days' or '2 hours'; a negative one ('-1 day') removes the cookie. Instead of expires you can pass the options object with expires inside it.

Options: domain, path (default /), secure (default the default_cookies_secure config), httponly, and samesite (Lax, Strict or None; default Lax, the default_cookies_samesite config).

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

function home() {
	var session = this.cookie('session');
	this.plain(session);
}
Remove
this.cookie('session', '', '-1 day');
method

controller.header(name, value)

Sets a header of the response.
ParameterTypeDescription
name String The name of the header.
value String The value.

Returns Controller The controller.

A header
this.header('X-Total', '42');
this.json(items);
method

controller.nocache()

Disables the HTTP cache of the answer.

Returns Controller The controller.

Fresh data
function stats() {
	this.nocache();
	this.json(getstats());
}
method

controller.csrf()

since 0.0.37 Creates a CSRF token for the current request.

Returns String The token.

Routes with the csrf flag verify the token from the x-csrf-token header or from the ?csrf= argument of the URL. In views the same token is @{csrf}.

Send the token
exports.install = function() {
	ROUTE('GET /api/token/', token);
	ROUTE('POST /api/save/ csrf', save);
};

function token() {
	this.json({ token: this.csrf() });
}
method

controller.autoclear([enable])

Keeps or removes the uploaded files when the request ends.
ParameterTypeDescription
enable? Boolean false keeps the files. Default: true

Returns Controller The controller.

autoclear(false) keeps the temporary files of controller.files after the answer, for work that continues later. controller.clear() removes them immediately.

Process later
function upload() {
	this.autoclear(false);
	var file = this.files[0];
	this.success();
	// file.path stays on the disk: process it, then remove it
}
method

controller.sse(data, [eventname], [id], [retry])

Sends a server-sent event.
ParameterTypeDescription
data String|Object The data of the event.
eventname? String The name of the event.
id? String The ID of the event.
retry? Number How long the browser waits before it reconnects, in milliseconds.

Returns Boolean false when the event cannot be sent (the client disconnected or the request was answered).

The first call answers with the headers of text/event-stream and keeps the connection open. An object is serialized as JSON. When retry is missing, the first call uses the timeout of the route. The previous event ID sent by the browser is in controller.sseID. The stream ends with controller.close().

A clock
exports.install = function() {
	ROUTE('GET /clock/', clock, ['delay']);
};

function clock() {
	var self = this;
	var timer = setInterval(function() {
		if (!self.sse({ time: new Date() }))
			clearInterval(timer);
	}, 1000);
}
method

controller.proxy(options)

Forwards the request to another URL and answers with its response.
ParameterTypeDescription
options Object|String The target URL, or the options.

Returns undefined Nothing.

The method, body, query string and headers of the request are sent to the target (except host, connection, accept-encoding and the x-forwarded-* headers). The status and the body of the response are answered back. On error it calls controller.invalid(err).

Options: url (required), method, headers, timeout (default 10000 ms) and callback(err, response), which runs before the answer.

Forward an API
exports.install = function() {
	ROUTE('GET /api/weather/', weather);
};

function weather() {
	this.proxy('https://api.example.com/weather');
}
method

controller.baa([label])

Reads Basic access authentication, or asks the browser for it.
ParameterTypeDescription
label? String The realm shown by the browser.

Returns Object|null The credentials without a label; null with a label.

Without an argument it returns { user, password, empty } from the Authorization header. With a label it answers 401 with the WWW-Authenticate header, so the browser shows a login dialog.

A protected page
function admin() {
	var auth = this.baa();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.baa('Administration');
		return;
	}
	this.view('admin');
}
property

controller.isConnected

Tells whether the client is still connected.

Returns Boolean

It is false after the client closed the connection or after controller.close(). Check it in long work before you answer.

Long work
function report() {
	var self = this;
	// longtask(callback) is your own function
	longtask(function(err, data) {
		if (self.isConnected)
			self.json(data);
	});
}
property

controller.isController

Always true for a controller.

Returns Boolean

Useful to tell a controller from a $ object in a shared function.

A shared function
function getuser(ctx) {
	return ctx.isController ? ctx.user : ctx.controller.user;
}
property

controller.secured

Tells whether the request came over HTTPS.

Returns Boolean

It is true when the protocol is https: (or wss:). Behind a proxy it depends on the URL the framework sees. Same as req.secured.

Force HTTPS
function index() {
	if (!this.secured)
		return this.redirect('https://' + this.req.host + this.url);
	this.view('index');
}
property

controller.referrer

The Referer header of the request.

Returns String

An empty string when the header is missing.

Go back
function back() {
	this.redirect(this.referrer || '/');
}
property

controller.robot

Tells whether the user agent looks like a bot.

Returns Boolean

It tests the User-Agent header for words like bot, crawler and spider.

Example
function index() {
	if (this.robot)
		return this.plain('Hello robot');
	this.view('index');
}
property

controller.ua

The parsed user agent as a short text with the browser and the system.

Returns String

Use req.useragent(true) for an object with the browser, the OS and the device. Same as req.ua.

Example
function index() {
	console.log(this.ua);
	this.view('index');
}
property

controller.uri

The parsed URL of the request.

Returns Object

An object of url.parse() with pathname, query, hostname and the other parts.

Example
function index() {
	this.plain(this.uri.pathname + ' ' + (this.uri.query || ''));
}
property

controller.split

The parts of the path of the URL.

Returns String[]

/products/shoes/ gives ['products', 'shoes'].

Example
// GET /docs/{page}/
function docs() {
	this.plain(this.split.join(' > '));
}
property

controller.subdomain

The subdomain of the request as an array.

Returns String[]

shop.eu.example.com gives ['shop', 'eu']; www is ignored. It is null without a subdomain.

Example
function index() {
	var tenant = this.subdomain ? this.subdomain[0] : 'default';
	this.view('index', { tenant: tenant });
}
property

controller.sessionid

The id of the session of the request.

Returns String

Set by your AUTH() delegate or by the session mechanism. Same as req.sessionid.

Example
function logout() {
	// removesession(id) is your own function
	removesession(this.sessionid);
	this.redirect('/');
}
property

controller.sseID

The id of the last event the browser received.

Returns String

The value of the Last-Event-ID header that the browser sends when it reconnects to a server-sent events route, or null.

Example
function events() {
	var last = this.sseID;
	this.sse({ resumed: !!last });
}
property

controller.route

The route that the request matched.

Returns Object

An internal object of the framework with the URL, the flags, the schema and the options of the route. Read it, do not change it.

Example
function index() {
	console.log(this.route.url);
	this.empty();
}
property

controller.options

The custom options of the route.

Returns Object

The object that you pass to ROUTE() as options.

Example
exports.install = function() {
	ROUTE('GET /reports/', report, { title: 'Reports' });
};

function report() {
	this.plain(this.options.title);
}
property

controller.flags

The flags of the route.

Returns String[]

An array with the flags of the route, for example ['get', 'json'].

Example
function index() {
	this.json(this.flags);
}
property

controller.schema

The name of the schema of the route.

Returns String

For a route like POST /api/users/ *Users --> save it is 'Users'. An empty string when the route has no schema.

Example
function action() {
	console.log(this.schema);
	this.empty();
}
property

controller.name

The name of the controller.

Returns String

The name of the file in /controllers/ (without .js) that declared the route.

Example
function index() {
	this.plain(this.name);
}
property

controller.breadcrumb

The breadcrumb of the current sitemap item.

Returns Object[]

The items set by controller.sitemap(); in views the same list is in @{sitemap}.

Example
function detail() {
	this.sitemap('detail');
	this.json(this.breadcrumb);
}
method

controller.jsonp(name, obj, [headers], [beautify], [replacer])

Answers with JSONP: a call of a JavaScript function with the data.
ParameterTypeDescription
name String The name of the JavaScript function.
obj Object The data.
headers? Object Extra response headers.
beautify? Boolean Formats the JSON. Default: false
replacer? Function A replacer for JSON.stringify().

Returns Controller The controller.

The body is name(json) with the content type application/x-javascript. Without name the function is callback. An ErrorBuilder is answered as its errors.

Name from the query string
function data() {
	this.jsonp(this.query.callback, { count: 10 });
}
method

controller.throw400([problem])

Answers with the error page 400 Bad Request.
ParameterTypeDescription
problem? String A description of the problem.

Returns Controller The controller.

It runs the route #400 when you declared one; otherwise the framework renders its own error page. The problem is in controller.exception of the error route. Alias: controller.view400().

Answer 400
function action() {
	this.throw400('Bad Request');
}
method

controller.throw401([problem])

Answers with the error page 401 Unauthorized.
ParameterTypeDescription
problem? String A description of the problem.

Returns Controller The controller.

It runs the route #401 when you declared one; otherwise the framework renders its own error page. The problem is in controller.exception of the error route. Alias: controller.view401().

Answer 401
function action() {
	this.throw401('Unauthorized');
}
method

controller.throw409([problem])

Answers with the error page 409 Conflict.
ParameterTypeDescription
problem? String A description of the problem.

Returns Controller The controller.

It runs the route #409 when you declared one; otherwise the framework renders its own error page. The problem is in controller.exception of the error route. Alias: controller.view409().

Answer 409
function action() {
	this.throw409('Conflict');
}
method

controller.throw501([problem])

Answers with the error page 501 Not Implemented.
ParameterTypeDescription
problem? String A description of the problem.

Returns Controller The controller.

It runs the route #501 when you declared one; otherwise the framework renders its own error page. The problem is in controller.exception of the error route. Alias: controller.view501().

Answer 501
function action() {
	this.throw501('Not Implemented');
}
method

controller.throw503([problem])

Answers with the error page 503 Service Unavailable.
ParameterTypeDescription
problem? String A description of the problem.

Returns Controller The controller.

It runs the route #503 when you declared one; otherwise the framework renders its own error page. The problem is in controller.exception of the error route. Alias: controller.view503().

Answer 503
function action() {
	this.throw503('Service Unavailable');
}
method

controller.view400([problem])

Alias of controller.throw400().
ParameterTypeDescription
problem? String The problem.

Returns Controller The controller.

It answers the error page 400 in the same way.

Same as throw400()
function detail() {
	this.view400();
}
method

controller.view401([problem])

Alias of controller.throw401().
ParameterTypeDescription
problem? String The problem.

Returns Controller The controller.

It answers the error page 401 in the same way.

Same as throw401()
function detail() {
	this.view401();
}
method

controller.view403([problem])

Alias of controller.throw403().
ParameterTypeDescription
problem? String The problem.

Returns Controller The controller.

It answers the error page 403 in the same way.

Same as throw403()
function detail() {
	this.view403();
}
method

controller.view404([problem])

Alias of controller.throw404().
ParameterTypeDescription
problem? String The problem.

Returns Controller The controller.

It answers the error page 404 in the same way.

Same as throw404()
function detail() {
	this.view404();
}
method

controller.view409([problem])

Alias of controller.throw409().
ParameterTypeDescription
problem? String The problem.

Returns Controller The controller.

It answers the error page 409 in the same way.

Same as throw409()
function detail() {
	this.view409();
}
method

controller.view500([error])

Alias of controller.throw500().
ParameterTypeDescription
error? Error The error, logged by the framework.

Returns Controller The controller.

It answers the error page 500 in the same way.

Same as throw500()
function detail() {
	this.view500();
}
method

controller.view501([problem])

Alias of controller.throw501().
ParameterTypeDescription
problem? String The problem.

Returns Controller The controller.

It answers the error page 501 in the same way.

Same as throw501()
function detail() {
	this.view501();
}
method

controller.view503([problem])

Alias of controller.throw503().
ParameterTypeDescription
problem? String The problem.

Returns Controller The controller.

It answers the error page 503 in the same way.

Same as throw503()
function detail() {
	this.view503();
}
method

controller.nocontent([headers])

Answers 204 No Content without a body.
ParameterTypeDescription
headers? Object Extra response headers.

Returns Controller The controller.

Nothing to answer
function ping() {
	this.nocontent();
}
method

controller.destroy()

Closes the connection without an answer.

Returns Controller The controller.

The socket is destroyed. Nothing happens when the request was already answered.

Drop a request
function upload() {
	if (this.req.headers['content-length'] > 1000000)
		return this.destroy();
	this.success();
}
method

controller.close([end])

Ends the answer, mostly a stream of server-sent events.
ParameterTypeDescription
end? Boolean Calls res.end(). Default: true

Returns Controller The controller.

It ends the response of controller.sse() and marks the controller as disconnected. With end set to false the response is only marked as finished.

Stop a stream
function events() {
	var self = this;
	self.sse({ step: 1 });
	setTimeout(function() {
		self.close();
	}, 5000);
}
method

controller.cancel()

Marks the controller as canceled.

Returns Controller The controller.

It sets controller.isCanceled to true. Called in a handler of ON('controller'), it stops the action of the route from running, so the handler must answer itself.

Stop requests in maintenance
ON('controller', function(controller) {
	if (CONF.maintenance) {
		controller.cancel();
		controller.throw503('Maintenance');
	}
});
method

controller.clear()

Removes the uploaded files of the request now.

Returns Controller The controller.

The temporary files of controller.files are deleted and body, query and the cookies of the request are cleared.

After the work
function upload() {
	var self = this;
	var file = self.files[0];
	file.move(PATH.databases(file.filename), function() {
		self.clear();
		self.success();
	});
}
method

controller.custom()

Lets you answer with the Node.js response yourself.

Returns Boolean true when you can answer.

The framework marks the request as answered and stops waiting for it. Then write to controller.res with writeHead() and end(). It returns false when the request was already answered.

Write the response
function raw() {
	if (this.custom()) {
		this.res.writeHead(200, { 'Content-Type': 'text/plain' });
		this.res.end('OK');
	}
}
method

controller.error(err)

Logs an error with the name of the controller and the URL.
ParameterTypeDescription
err Error|String The error.

Returns Controller The controller.

The error goes to F.error() and to controller.exception; the request is not answered. An ErrorBuilder is answered as JSON instead.

Log and continue
function action() {
	this.error(new Error('Cache is empty'));
	this.json([]);
}
method

controller.successful(callback)

Creates a callback that answers the error and passes only the result on.
ParameterTypeDescription
callback Function Runs on success with the results.

Returns Function A callback (err, a, b, c).

The returned function has the form (err, a, b, c). On error it calls controller.invalid(err); otherwise it calls callback(a, b, c) with the controller as this.

Only the success path
function detail(id) {
	NOSQL('products').one().where('id', id).callback(this.successful(function(item) {
		this.view('detail', item);
	}));
}
method

controller.hostname([path])

Creates an absolute URL with the host of the request.
ParameterTypeDescription
path? String A path to add.

Returns String The URL, for example https://example.com/products/.

The protocol, the host name and the port of the request with path added.

A link for an email
function invite() {
	this.json({ url: this.hostname('/invite/' + UID() + '/') });
}
method

controller.image(filename, make, [headers], [callback])

Answers with an image changed by the image processor.
ParameterTypeDescription
filename String|Stream The image.
make Function function(image).
headers? Object Extra response headers.
callback? Function Runs when the response ends.

Returns Controller The controller.

filename is a file in /public/ (or a full path with ~ in front) or a stream. make(image) changes the image with the methods of Image (resize(), quality(), ...). The result is cached in /tmp/. It needs GraphicsMagick or ImageMagick.

A thumbnail
function thumbnail() {
	this.image('/img/photo.jpg', function(image) {
		image.resize(200, 200);
		image.quality(80);
	});
}
method

controller.memorize(key, expire, [disabled], fn, [fnFrom])

Caches the whole answer of an action.
ParameterTypeDescription
key String The key in the cache.
expire String|Date How long, for example '5 minutes'.
disabled? Boolean true skips the cache. Default: false
fn Function Creates the answer; runs with the controller as this.
fnFrom? Function Runs before an answer from the cache.

Returns Controller The controller.

The first call runs fn and stores the answer (a view, JSON or text) under key for expire. Later calls answer from the cache, and fnFrom runs before that. With disabled set to true the cache is skipped. The theme is added to the key.

Cache the home page
function index() {
	this.memorize('home', '5 minutes', DEBUG, function() {
		this.view('index');
	});
}
method

controller.description(value)

Sets the meta description of the page.
ParameterTypeDescription
value String The description.

Returns Controller The controller.

In the layout it is written by @{meta}. controller.keywords() sets the keywords and controller.author() the author the same way.

Meta tags
function index() {
	this.title('Shop');
	this.description('Shoes and clothes');
	this.view('index');
}
method

controller.keywords(value)

Sets the meta keywords of the page.
ParameterTypeDescription
value String|Array The keywords.

Returns Controller The controller.

An array is joined with commas. In the layout it is written by @{meta}.

Keywords
function index() {
	this.keywords(['shoes', 'clothes']);
	this.view('index');
}
method

controller.head([value], [...])

Adds tags into the head of the layout, or reads them.
ParameterTypeDescription
value? String A file name or an HTML tag.

Returns Controller|String The controller, or the HTML without arguments.

A .css file becomes a <link> and a .js file a <script>; relative names point to /public/css/ and /public/js/. A value that starts with < is added as it is. Each value is added once. Without arguments it returns the HTML; in the layout use @{head}.

Files for one page
function editor() {
	this.head('editor.css', 'editor.js');
	this.view('editor');
}
method

controller.place(name, [value], [...])

Adds content into a named place of the layout, or reads it.
ParameterTypeDescription
name String The name of the place.
value? String The content.

Returns Controller|String The controller, or the content with only name.

A .js value becomes a <script> and a .css value a <link>; other values are added as they are. In the layout use @{place('name')}.

Scripts at the end of the page
function index() {
	this.place('footer', '/js/chart.js');
	this.view('index');
}
method

controller.theme(name)

Sets the theme of the views of this request.
ParameterTypeDescription
name String The name of the theme.

Returns Controller The controller.

Views, layouts and static files are then looked up in /themes/{name}/ first. The default comes from CONF.default_theme.

A theme per customer
function index() {
	this.theme(this.query.dark ? 'dark' : 'default');
	this.view('index');
}
method

controller.component(name, [settings], [model])

Renders a component to HTML.
ParameterTypeDescription
name String The name of the component.
settings? Object The settings of the component.
model? Object The model; the model of the view by default.

Returns String The HTML, or an empty string for an unknown component.

The component is a file in /components/. Its CSS and JS are added to the head of the layout. In views use @{component('name')}.

HTML of a component
function widget() {
	this.html(this.component('chart', { color: 'red' }));
}
method

controller.helper(name, [arg], [...])

Runs a view helper from DEF.helpers.
ParameterTypeDescription
name String The name of the helper.
arg? Object Arguments for the helper.

Returns String The output of the helper.

The helper runs with the controller as this. An unknown helper returns an empty string.

Use a helper in an action
DEF.helpers.price = function(value) {
	return value.format(2) + ' EUR';
};

function price() {
	this.plain(this.helper('price', 10));
}
method

controller.public(name, [path])

Creates the URL of a file in /public/.
ParameterTypeDescription
name String The file.
path? String A path joined to a relative URL.

Returns String The URL.

It respects the static URL settings and the theme. The family controller.public_js(), public_css(), public_image(), public_video(), public_font() and public_download() does the same for its own directory.

A URL in JSON
function config() {
	this.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });
}
method

controller.public_js(name, [tag])

Creates the URL of a file in the public js directory.
ParameterTypeDescription
name String The file.
tag? Boolean Returns an HTML tag. Default: false

Returns String The URL.

The directory comes from the configuration (static_url_script, default /js/). With tag set to true it returns the HTML tag (<script> or <link>).

URL of a file
function index() {
	this.plain(this.public_js('app.js'));
}
method

controller.public_css(name, [tag])

Creates the URL of a file in the public css directory.
ParameterTypeDescription
name String The file.
tag? Boolean Returns an HTML tag. Default: false

Returns String The URL.

The directory comes from the configuration (static_url_style, default /css/). With tag set to true it returns the HTML tag (<script> or <link>).

URL of a file
function index() {
	this.plain(this.public_css('app.css'));
}
method

controller.public_image(name)

Creates the URL of a file in the public img directory.
ParameterTypeDescription
name String The file.

Returns String The URL.

The directory comes from the configuration (static_url_image, default /img/).

URL of a file
function index() {
	this.plain(this.public_image('logo.png'));
}
method

controller.public_video(name)

Creates the URL of a file in the public videos directory.
ParameterTypeDescription
name String The file.

Returns String The URL.

The directory comes from the configuration (static_url_video, default /videos/).

URL of a file
function index() {
	this.plain(this.public_video('intro.mp4'));
}
method

controller.public_font(name)

Creates the URL of a file in the public fonts directory.
ParameterTypeDescription
name String The file.

Returns String The URL.

The directory comes from the configuration (static_url_font, default /fonts/).

URL of a file
function index() {
	this.plain(this.public_font('icons.woff2'));
}
method

controller.public_download(name)

Creates the URL of a file in the public download directory.
ParameterTypeDescription
name String The file.

Returns String The URL.

The directory comes from the configuration (static_url_download, default /download/).

URL of a file
function index() {
	this.plain(this.public_download('manual.pdf'));
}
method

controller.runtest(url, [name], [callback])

Adds a test of a route in the tests of the framework.
ParameterTypeDescription
url String The route to test.
name? String The name of the test.
callback? Function function(result) that returns true on success.

Returns Object The test.

The tests of one controller run one after another. url is a route like 'GET /api/products/' or 'API /api/ products_query' (then the name of the test is the operation). callback(result) gets { err, value, response, name } and returns true when the test passes; without it, a test passes when there is no error.

Test routes from a route
function selftest() {
	this.runtest('GET /api/products/', function(result) {
		return !result.err && result.value instanceof Array;
	});
	this.success();
}
property

req.host

The Host header of the request.

Returns String

The host name with the port, for example example.com:8000.

Example
function index() {
	this.plain(this.req.host);
}
property

req.secured

Tells whether the request came over HTTPS.

Returns Boolean

It is true when the protocol is https: or wss:.

Example
MIDDLEWARE('https', function($) {
	if ($.req.secured)
		$.next();
	else
		$.res.redirect('https://' + $.req.host + $.req.url);
});
property

req.isAuthorized

The result of the authorization.

Returns Boolean

It is true until your AUTH() delegate runs, then it is true when the delegate accepted the user and false when it rejected it.

Example
function index() {
	this.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');
}
property

req.isStaticFile

Tells whether the request asks for a static file.

Returns Boolean

It is true when the URL has a file extension and static files are allowed. Useful in DEF.onLocale and middleware.

Example
DEF.onLocale = function(req) {
	return req.isStaticFile ? '' : (req.query.lang || 'en');
};
property

req.xhr

Tells whether the request came from JavaScript.

Returns Boolean

It is true when the header X-Requested-With is XMLHttpRequest.

Example
function index() {
	if (this.req.xhr)
		this.json({ ok: true });
	else
		this.view('index');
}
property

req.ip

The IP address of the client.

Returns String

Behind a proxy it is the first address of X-Forwarded-For. It can be set.

Example
function index() {
	this.plain(this.req.ip);
}
property

req.uri

The parsed URL of the request.

Returns Object

An object of url.parse() with pathname, query, hostname and port.

Example
function index() {
	this.plain(this.req.uri.pathname);
}
property

req.path

The parts of the path in lower case.

Returns String[]

/Products/Shoes/ gives ['products', 'shoes']. req.split keeps the original case.

Example
function index() {
	this.json(this.req.path);
}
property

req.split

The parts of the path of the URL.

Returns String[]

The parts as they were in the URL. Same as controller.split.

Example
function index() {
	this.json(this.req.split);
}
property

req.subdomain

The subdomain as an array, or null.

Returns String[]

www is ignored. a.localhost gives ['a'].

Example
function index() {
	this.json(this.req.subdomain);
}
property

req.mobile

Tells whether the user agent is a mobile device.

Returns Boolean

It tests the User-Agent header. It can be set.

Example
function index() {
	this.view(this.req.mobile ? 'mobile' : 'index');
}
property

req.robot

Tells whether the user agent looks like a bot.

Returns Boolean

It tests the User-Agent header.

Example
function index() {
	this.plain(this.req.robot ? 'bot' : 'human');
}
property

req.ua

The parsed user agent as a short text with the browser and the system.

Returns String

The same as req.useragent().

Example
function index() {
	this.plain(this.req.ua);
}
property

req.query

The query string as an object.

Returns Object

It is parsed on the first read and can be set.

Example
function index() {
	this.json(this.req.query);
}
property

req.body

The parsed body of the request.

Returns Object

A JSON or form body. Same as controller.body.

Example
function save() {
	this.json(this.req.body);
}
property

req.files

The uploaded files.

Returns HttpFile[]

An array of HttpFile objects for routes with the upload flag. Same as controller.files.

Example
function upload() {
	this.json(this.req.files.map(function(file) {
		return file.filename;
	}));
}
property

req.user

The user accepted by the AUTH() delegate, or null.

Returns Object

Same as controller.user.

Example
function index() {
	this.json(this.req.user);
}
property

req.session

The session object of the request, or null.

Returns Object

Set by your AUTH() delegate or the session mechanism. Same as controller.session.

Example
function index() {
	this.json(this.req.session);
}
method

req.useragent([structured])

Parses the User-Agent header.
ParameterTypeDescription
structured? Boolean Returns an object. Default: false

Returns String|Object The user agent.

Without an argument it returns a short text with the names found in the header, such as the browser and the system. With true it returns { os, browser, device }, where device is desktop, mobile, tablet or tv. The result is cached on the request.

Details of the device
function index() {
	this.json(this.req.useragent(true));
}
method

req.cookie(name)

Reads a cookie of the request.
ParameterTypeDescription
name String The name of the cookie.

Returns String The value.

The value is decoded. A missing cookie gives an empty string. controller.cookie(name) does the same.

Read a cookie in middleware
MIDDLEWARE('lang', function($) {
	$.req.$language = $.req.cookie('lang') || 'en';
	$.next();
});
method

req.authorization()

Reads the Basic authorization header.

Returns Object { user, password, empty }.

It decodes Authorization: Basic ... to { user, password, empty }. empty is true when the user or the password is missing.

Basic auth
function admin() {
	var auth = this.req.authorization();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.header('WWW-Authenticate', 'Basic realm="Admin"');
		return this.throw401();
	}
	this.view('admin');
}
method

req.authorize(callback)

Runs the AUTH() delegate for this request yourself.
ParameterTypeDescription
callback Function function(err, user, isAuthorized).

Returns Request The request.

callback(err, user, isAuthorized) gets the result of the delegate. Without a delegate isAuthorized is false. Useful for routes that do not use the authorization flags.

Check a user on a public route
function index() {
	var self = this;
	self.req.authorize(function(err, user, isAuthorized) {
		self.view('index', { user: isAuthorized ? user : null });
	});
}
method

req.clear()

Removes the uploaded files of the request.

Returns Request The request.

Same as controller.clear().

Clear the files
function upload() {
	this.req.clear();
	this.success();
}
method

req.csrf()

since 0.0.37 Creates a CSRF token for the request.

Returns String The token.

Same as controller.csrf(); it uses DEF.onCSRFcreate(req).

A token in middleware
MIDDLEWARE('token', function($) {
	$.res.setHeader('X-CSRF-Token', $.req.csrf());
	$.next();
});
method

req.encrypt([enable])

Encrypts the text answer of this request.
ParameterTypeDescription
enable? Boolean false turns it off. Default: true

Returns Request The request.

The answer is encrypted with CONF.secret_encryption and gets the header X-Encryption: a. controller.encrypt([enable]) does the same.

Encrypt one answer
function secret() {
	this.req.encrypt();
	this.json({ token: UID() });
}
method

req.hostname([path])

Creates an absolute URL with the host of the request.
ParameterTypeDescription
path? String A path to add.

Returns String The URL.

The protocol, the host name and the port of the request with path added. Same as controller.hostname().

Absolute URL
function index() {
	this.plain(this.req.hostname('/login/'));
}
method

req.nocache()

Disables the HTTP cache of the answer.

Returns Request The request.

It calls res.nocache().

In middleware
MIDDLEWARE('nocache', function($) {
	$.req.nocache();
	$.next();
});
property

res.controller

The controller of the request.

Returns Controller

Set when a controller handles the request.

Example
MIDDLEWARE('log', function($) {
	console.log($.res.controller ? 'controller' : 'no controller');
	$.next();
});
property

res.success

Tells whether the response was sent.

Returns Boolean

It is true after the framework answered the request.

Example
function action() {
	var self = this;
	setTimeout(function() {
		if (!self.res.success)
			self.empty();
	}, 1000);
}
property

res.nocompress

Turns off the compression of HTML and static files for this response.

Returns Boolean

With true the framework does not minify the HTML and the static files it sends.

Example
MIDDLEWARE('raw', function($) {
	$.res.nocompress = true;
	$.next();
});
method

res.json(obj)

Answers with an object as JSON.
ParameterTypeDescription
obj Object The value.

Returns Response The response.

The status comes from the response options (200 by default).

JSON from a route with (req, res)
ROUTE('GET /api/ping/', function(req, res) {
	res.json({ ok: true });
});
method

res.content(code, body, type, [compress], [headers])

Answers with a body and a content type.
ParameterTypeDescription
code Number The HTTP status.
body String The body.
type String The content type.
compress? Boolean Compression.
headers? Object Extra response headers.

Returns Response The response.

Bodies over 4 kB are compressed with GZIP.

A CSV
ROUTE('GET /export/', function(req, res) {
	res.content(200, 'id;name\n1;Peter', 'text/csv');
});
method

res.send([code], body, [type])

Answers in the style of Express.
ParameterTypeDescription
code? Number The HTTP status. Default: 200
body String|Object|Number The body.
type? String The content type.

Returns Response The response.

A string is text/html, a number is answered as the text of that status, an object is JSON and an ErrorBuilder is answered as its errors. It is meant for middleware written for Express.

Express style
ROUTE('GET /hello/', function(req, res) {
	res.send('<b>Hello</b>');
});
method

res.binary(buffer, type, [encoding], [download], [headers])

Answers with a buffer.
ParameterTypeDescription
buffer Buffer The data.
type String The content type.
encoding? String The encoding of the buffer.
download? String A file name to download.
headers? Object Extra response headers.

Returns Response The response.

download sets the file name of Content-Disposition.

A generated file
ROUTE('GET /file/', function(req, res) {
	res.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');
});
method

res.image_nocache(input, make, [headers], [callback])

Answers with a changed image without the cache of /tmp/.
ParameterTypeDescription
input String|Stream The image.
make Function function(image).
headers? Object Extra response headers.
callback? Function Runs at the end.

Returns Response The response.

Works like res.image(), but the result is created for every request.

Image with a timestamp
ROUTE('GET /stamp/', function(req, res) {
	res.image_nocache(PATH.public('img/photo.jpg'), function(image) {
		image.resize(300, 200);
	});
});
method

res.nocache()

Disables the HTTP cache of the response.

Returns Response The response.

It removes If-None-Match and If-Modified-Since from the request and sets Cache-Control: private, no-cache, no-store, max-age=0.

In a route with (req, res)
ROUTE('GET /now/', function(req, res) {
	res.nocache();
	res.json({ now: new Date() });
});
method

res.throw409([problem])

Answers with the error page 409 Conflict.
ParameterTypeDescription
problem? String A description of the problem.

Returns Response The response.

It runs the route #409 when you declared one.

Answer 409
ROUTE('GET /legacy/', function(req, res) {
	res.throw409();
});
method

res.throw501([problem])

Answers with the error page 501 Not Implemented.
ParameterTypeDescription
problem? String A description of the problem.

Returns Response The response.

It runs the route #501 when you declared one.

Answer 501
ROUTE('GET /legacy/', function(req, res) {
	res.throw501();
});
Made in Europe