---
title: Migrar desde Total.js 4
project: Total.js V5
version: 0.0.20
section: guides
language: es
license: MIT
url: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/migrating-from-total4/
updated: 2026-11-18T16:59:59.647Z
---

# Migrar desde Total.js 4

> Lleva una aplicación de Total.js 4 a Total.js 5, área por área, con el código antes y después de cada cambio.

Esta guía lleva una aplicación de Total.js 4 a Total.js 5. Enumera lo que tienes que cambiar en cada área, con el código antiguo junto a su sustituto, y termina con una pequeña aplicación mostrada en las dos versiones.

## Orden de trabajo recomendado

1. Sustituye el paquete `total4` por `total5` y actualiza el [script de inicio](#start-script).
2. Renombra las [claves de configuración](#configuration) y añade tipos a los valores numéricos.
3. Convierte los [esquemas en acciones](#schemas-and-actions) y actualiza las rutas que los llaman.
4. Sustituye `this` por `$` en las [rutas y controladores](#routes) y en el [middleware](#middleware).
5. Revisa las [vistas](#views) y las [vistas de correo](#mail): carpetas, layouts y títulos.
6. Actualiza las consultas [NoSQL](#nosql), la gestión de errores de [RESTBuilder](#restbuilder), los [WebSockets](#websockets) y el [almacenamiento de archivos](#file-storage).
7. Sustituye [`SCHEDULE()`](#scheduling), las [operaciones y tareas](#operations-and-tasks), y las [llamadas](#modules-models-and-definitions) a `MODULE()` y `MODEL()`.
8. Reescribe las [pruebas unitarias](#unit-tests) y ejecuta la aplicación.

## Script de inicio

| Total.js 4 | Total.js 5 |
| --- | --- |
| `npm install total4` | `npm install total5@beta` |
| `require('total4/debug')(options)` | `require('total5'); Total.run(options)` |
| `require('total4/release')(options)` | `options.release = true; Total.run(options)` |

Antes:

```js
const options = {};

// options.ip = '127.0.0.1';
options.port = parseInt(process.argv[2]);
// options.config = { name: 'My app' };

var type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';
require('total4/' + type)(options);
```

Después:

```js
require('total5');

const options = {};

// options.ip = '127.0.0.1';
options.port = parseInt(process.argv[2]);
// options.config = { name: 'My app' };

options.release = process.argv.includes('--release');

Total.run(options);
```

Los dos scripts arrancan en modo de depuración, y en modo release con `node index.js --release`. Consulta [Instalación](../installation/).

## Esquemas y acciones

`schema.define()` y la familia de `schema.setInsert()` no existen en Total.js 5. Un esquema sin cambios detiene la aplicación al arrancar con `TypeError: schema.define is not a function`. Mueve cada operación a un `NEWACTION()` en la carpeta `actions/` y declara sus campos en `input`.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` |
| `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\|user}'` |
| `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` |
| `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` |
| `$.id` | `params: '*id:String'` y `$.params.id` |
| `.callback($.callback)` | `.callback($)` |
| `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` |
| `CALL('Math --> double', data)` | `ACTION('Math/double', data)` |

Antes:

```js
NEWSCHEMA('Users', function(schema) {

	schema.define('name', 'String(30)', true);
	schema.define('email', 'Email', true);
	schema.define('age', Number);
	schema.define('role', ['admin', 'user']);

	schema.setInsert(function($, model) {
		model.id = 'A1';
		$.success(model);
	});

});
```

```js
exports.install = function() {
	ROUTE('POST /api/users/ *Users --> insert');
};
```

Después:

```js
NEWACTION('Users/insert', {
	input: '*name:String(30), *email:Email, age:Number, role:{admin|user}',
	action: function($, model) {
		model.id = 'A1';
		$.success(model);
	}
});
```

```js
exports.install = function() {
	ROUTE('POST /api/users/ --> Users/insert');
};
```

### Validadores personalizados

Una función de validación de `schema.define()` pasa a la acción.

Antes:

```js
NEWSCHEMA('Signup', function(schema) {

	schema.define('name', 'String(30)', true);
	schema.define('age', Number, value => value >= 18, 'You must be an adult');

	schema.setInsert(function($, model) {
		$.success(model.age);
	});

});
```

Después:

```js
NEWACTION('Signup/insert', {
	input: '*name:String(30), age:Number',
	action: function($, model) {

		if (model.age < 18) {
			$.invalid('You must be an adult', 'age');
			return;
		}

		$.success(model.age);
	}
});
```

### Esquemas que ya usan `schema.action()`

Estos esquemas siguen funcionando. Solo cambia la ruta: `*Tags --> list` pasa a ser `--> Tags/list`.

```js
NEWSCHEMA('Tags', function(schema) {

	schema.action('list', {
		name: 'List of tags',
		query: 'limit:Number',
		action: function($) {
			$.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3));
		}
	});

	schema.action('create', {
		name: 'Create a tag',
		input: '*name:String(20)',
		action: function($, model) {
			$.success(model.name);
		}
	});

});
```

```js
exports.install = function() {
	ROUTE('GET  /api/tags/ --> Tags/list');
	ROUTE('POST /api/tags/ --> Tags/create');
};
```

### Valores y errores que notarán tus clientes

| Caso | Total.js 4 | Total.js 5 |
| --- | --- | --- |
| Falta un `Number` opcional | El campo vale `0` | El campo se omite |
| Falta un enum opcional | El campo se omite | El campo vale `''` |
| El valor del enum no está en la lista | Se descarta el valor y se acepta la petición | `400` con un error para el campo |
| Claves de un error de campo obligatorio | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` |
| Claves de un error de `$.invalid()` con un campo | `name`, `error` | `error`, `path` |

Un cliente que lea `name` de tus propios errores tiene que leer `path` en su lugar. Consulta [Acciones](../actions/) y [Esquemas JSON](../json-schemas/).

## Rutas

| Total.js 4 | Total.js 5 |
| --- | --- |
| `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` |
| `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)`: el método es obligatorio |
| `{page:number}` convierte el valor | `{page}` es una cadena: `$.params.page.parseInt()` |
| `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` |
| `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` |
| `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` y `UNAUTHORIZED($, 'admin')` en el manejador |
| `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` |
| `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` |

Una ruta sin flag de tamaño rechaza con `431` un cuerpo JSON de más de 256 kB, así que da un límite propio a las rutas que importan muchos datos. Un endpoint `API` desconocido responde `400` en lugar de `404`. Consulta [Enrutamiento](../routing/).

Antes:

```js
exports.install = function() {
	ROUTE('GET /users/{id}/orders/{order}/', detail);
};

function detail(id, order) {
	this.json({ id: id, order: order, params: this.params });
}
```

Después:

```js
exports.install = function() {
	ROUTE('GET /users/{id}/orders/{order}/', detail);
};

function detail($) {
	$.json({ id: $.params.id, order: $.params.order, params: $.params });
}
```

## Controladores

Los manejadores reciben el controlador como `$`. En las rutas HTTP, `this` ya no es el controlador.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `this.status = 201` | `$.response.status = 201` |
| `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` |
| `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` |
| `this.content('<a>1</a>', 'text/xml')` | `$.xml('<a>1</a>')` |
| `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` |
| `this.nocontent()` | `$.empty()` |
| `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` |
| `this.throw500('Problem')` | `$.fallback(500, 'Problem')` |
| `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` |
| `this.success(true, 42)` | `$.success(42)` |
| `this.success(false)` | `$.json({ success: false })` |
| `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` |
| `file.isImage()` | `file.isImage` |
| `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` |

En estos miembros basta con sustituir `this` por `$`: `params`, `query`, `body`, `files`, `headers`, `url`, `ip`, `ua`, `mobile`, `robot`, `xhr`, `referrer`, `user`, `language`, `cookie()`, `hostname()`, `json()`, `plain()`, `view()`, `filefs()` y `stream(type, stream)`.

Una ruta de error establece el estado de la misma manera:

```js
exports.install = function() {
	ROUTE('GET /missing/', missing);
	ROUTE('GET /denied/', denied);
	ROUTE('GET /broken/', broken);
	ROUTE('#404', notfound);
};

function missing($) {
	$.fallback(404);
}

function denied($) {
	$.fallback(403);
}

function broken($) {
	$.fallback(500, 'Unexpected problem');
}

function notfound($) {
	$.response.status = 404;
	$.plain('My 404 page');
}
```

Consulta [Controlador](../controller/).

## Vistas

La sintaxis de los archivos de vista no cambia: las expresiones, condiciones, bucles, secciones, vistas parciales y helpers de `DEF.helpers` funcionan como antes.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `this.view('detail')` en `controllers/users.js` encuentra `views/users/detail.html` | `$.view('users/detail')`: el nombre siempre parte de `views/` |
| El layout puede leer `model` | Establece `@{repository.name = model.name}` en la vista y lee `repository` en el layout |
| `this.title('Products')` | `@{title('Products')}` en la vista |
| `this.repository.page = 'list'` | `@{repository.page = 'list'}` en la vista |
| `VIEW('mail/order', model)` | `F.view('mail/order', model)`, con `@{layout('')}` en la vista |
| Al título de la página de inicio se le añaden ` - ` y `CONF.name` | El título de la página de inicio se queda tal como lo escribiste |

Antes:

```html
<title>@{model.name}</title>@{body}
```

Después:

```html
<title>@{repository.name}</title>@{body}
```

```html
@{repository.name = model.name}
<h1>@{model.name}</h1>
```

Consulta [Vistas](../views/).

## Middleware

| Total.js 4 | Total.js 5 |
| --- | --- |
| `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` |
| `$.res.throw401()` | `$.invalid(401)` |
| `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` |
| `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` |
| `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` |
| `USE('poweredby', ['web'])` | Tercer argumento `'routes'`, dentro de `ON('ready')` |

Antes:

```js
MIDDLEWARE('poweredby', function($) {
	$.res.setHeader('x-server', 'myapp');
	$.next();
});

USE('poweredby', ['web']);
```

Después:

```js
ON('ready', function() {
	NEWMIDDLEWARE('poweredby', function($, next) {
		$.response.headers['x-server'] = 'myapp';
		next();
	}, 'routes');
});
```

Consulta [Middleware](../middleware/).

## WebSockets

Una ruta `SOCKET` mantiene su estructura, y `this` sigue funcionando dentro de su manejador.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `function room(name) {}` | `function room($) { var name = $.params.name; }` |
| `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` |
| `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` |
| `client.send(text)` en una ruta de texto | `client.send(text, true)` |
| `client.close('finished', 4000)` | `client.close(4000, 'finished')` |
| Un cliente `+SOCKET` rechazado se conecta y se cierra con `4001` | Se rechaza el handshake y el cliente ve `1006` |

Consulta [WebSockets](../websockets/).

## NoSQL

Los archivos `.nosql` existentes se pueden leer tal cual. `insert()`, `find()`, `read()`, `update()`, `remove()`, `where()`, `search()`, `fields()`, `skip()`, `take()`, `first()` y el prefijo de actualización `+field` no cambian.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `find()` empieza por el documento más antiguo | `find()` empieza por el documento más reciente: añade `sort()` cuando importe el orden |
| `find2()` | `find()` |
| `one()` | `read()` |
| `sort('age_desc')` | `sort('age', true)` |
| `NOSQL('users').count()` | `DATA.count('nosql/users')` |
| `NOSQL('users').list()` | `DATA.list('nosql/users')` |
| `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` |
| `update({ '-score': 3 })` | `update({ '+score': -3 })` |
| `TABLE('users')` | `NOSQL('users')` |

`TABLE()` no existe en Total.js 5, así que tendrás que mover tú mismo las filas de los archivos `.table` a una base de datos NoSQL.

Antes:

```js
exports.install = function() {
	ROUTE('GET /run/', run);
};

async function run() {
	var db = NOSQL('users');
	await db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();
	await db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();
	await db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();

	var one = await db.one().where('id', '2').fields('name').promise();
	var count = await db.count().where('age', '>', 35).promise();
	var list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise();
	var rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise();

	await db.update({ '-score': 3 }).where('id', '1').promise();
	var score = await db.read().id('1').fields('score').promise();

	this.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });
}
```

Después:

```js
exports.install = function() {
	ROUTE('GET /run/', run);
};

async function run($) {
	var db = NOSQL('users');
	await db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();
	await db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();
	await db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();

	var one = await db.read().where('id', '2').fields('name').promise();
	var count = await DATA.count('nosql/users').where('age', '>', 35).promise();
	var list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise();
	var rule = await db.find().query('doc.age > 45').fields('name').promise();

	await db.update({ '+score': -3 }).where('id', '1').promise();
	var score = await db.read().id('1').fields('score').promise();

	$.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });
}
```

Consulta [Base de datos NoSQL](../nosql/).

## RESTBuilder

| Total.js 4 | Total.js 5 |
| --- | --- |
| Un estado de `400` o superior solo es un error con `.strict()` | Un estado de `400` o superior siempre es un error |
| `.callback($.callback)` en una operación | `.callback($)` en una acción |

El código que lee `output.status` después de una petición fallida tiene que gestionar antes `err`. Consulta [Peticiones HTTP](../http-requests/).

## Configuración

| Total.js 4 | Total.js 5 |
| --- | --- |
| `default_root` | `$root` |
| `default_timezone` | `$timezone` |
| `default_cookies_samesite` | `$cookiesamesite` |
| `default_cookies_secure` | `$cookiesecure` |
| `default_xpoweredby` | `$xpoweredby` |
| `allow_custom_titles` | `$customtitles` |
| `allow_gzip` | `$httpcompress` |
| `limit : 50` es un número | `limit (number) : 50`: sin tipo, el valor es una cadena |
| `smtp (object) : { port: 465 }` | `smtp (json) : { "port": 465 }` |
| `config-release` | No se carga: guarda los valores en `config` |

Antes:

```text
name                     : Shop
default_root             : /app/
default_timezone         : Europe/Bratislava
default_cookies_samesite : Strict
default_cookies_secure   : true
default_xpoweredby       : MyServer
allow_custom_titles      : true
allow_gzip               : false
```

Después:

```text
name            : Shop
$root           : /app/
$timezone       : Europe/Bratislava
$cookiesamesite : Strict
$cookiesecure   : true
$xpoweredby     : MyServer
$customtitles   : true
$httpcompress   : false
```

`CORS()`, `name`, los valores `(array)` y `mail_smtp_options` escrito como objeto JavaScript funcionan como antes. Consulta [Configuración](../configuration/).

## Autorización

El delegate `AUTH()`, los flags de ruta `+` y `-` y `UNAUTHORIZED()` no cambian. `SESSION()` no existe en Total.js 5: usa la sesión integrada de `AUTH()`.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `SESSION()` con `ondata` | `AUTH(opt)` con `opt.onread` |
| `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` |
| `session.remove2(userid)` y borrar la cookie | `opt.logout($)` en una acción |

Antes:

```js
var session = SESSION();

session.ondata = function(meta, next) {
	next(null, { id: meta.id, name: 'Peter' });
};

AUTH(function($) {
	session.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, function(err, user) {
		if (user)
			$.success(user);
		else
			$.invalid();
	});
});

MAIN.session = session;
```

Después:

```js
var opt = {};

opt.secret = 'session-key';
opt.cookie = 'sid';
opt.expire = '1 hour';

opt.onread = function(meta, next) {
	next(null, { id: meta.userid, name: 'Peter' });
};

AUTH(opt);
MAIN.session = opt;
```

```js
NEWACTION('Account/logout', {
	action: function($) {
		MAIN.session.logout($);
		$.success();
	}
});
```

`opt.logout()` elimina la sesión de la memoria y borra la cookie. Una copia guardada del token está firmada, así que se vuelve a aceptar siempre que `onread` devuelva un usuario. Comprueba la sesión en tu base de datos dentro de `onread` cuando cerrar la sesión tenga que revocar el token. Consulta [Autorización](../authorization/).

## Localización

Los archivos de recursos y `@(Text)` en las vistas siguen igual, y las claves generadas son idénticas.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` |
| `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` |
| `TRANSLATOR('sk', '<b>@(Welcome)</b>')` | `TRANSLATE('sk', '<b>@(Welcome)</b>')` |
| `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` |

Consulta [Localización](../localization/).

## Correo

| Total.js 4 | Total.js 5 |
| --- | --- |
| `MAIL()` renderiza la vista sin layout | `MAIL()` renderiza la vista dentro de `views/layout.html` |
| `ON('mail', fn)` | `ON('$mail', fn)` |
| `message.address_to` | `message.email_to` |

Empieza cada vista de correo con `@{layout('')}`. Sin esto, el mensaje se envuelve en el layout de tu sitio y, si `views/layout.html` no existe, el mensaje no llega a enviarse.

Antes:

```html
<p>Hello @{model.name}</p>
```

Después:

```html
@{layout('')}
<p>Hello @{model.name}</p>
```

Consulta [Envío de correo](../mail/).

## Almacenamiento de archivos

Los argumentos de `save()` cambian de orden: los datos personalizados ahora van antes del callback.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` |

`read()` y `$.filefs()` no cambian. Consulta [Almacenamiento de archivos](../file-storage/).

## Programación de tareas

| Total.js 4 | Total.js 5 |
| --- | --- |
| `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` |
| `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` |

Antes:

```js
MAIN.runs = 0;

SCHEDULE('* * * * *', function() {
	MAIN.runs++;
});
```

Después:

```js
MAIN.runs = 0;

CRON('* * * * *', function() {
	MAIN.runs++;
});
```

Consulta [Programación de tareas y eventos](../scheduling-and-events/).

## Operaciones y tareas

`NEWOPERATION()`, `OPERATION()`, `RUN()`, `NEWTASK()` y `TASK()` no existen en Total.js 5. Cada operación se convierte en una acción, y los pasos de una tarea se convierten en una acción o en varias acciones llamadas en secuencia.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` |
| `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` |
| `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` para cada paso |
| `NEWTASK('order', fn)` y `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` |

Antes:

```js
exports.install = function() {
	ROUTE('POST /order/', order);
	ROUTE('POST /chain/', chain);
};

function order() {
	var self = this;
	OPERATION('order_price', self.body, function(err, response) {
		self.json({ err: err ? err.toString() : null, response: response });
	});
}

function chain() {
	var self = this;
	RUN('order_check, order_price', self.body, function(err, response) {
		if (err)
			self.invalid(err);
		else
			self.json(response.order_price);
	});
}
```

Después:

```js
NEWACTION('order_check', {
	input: '*email:String, count:Number',
	action: function($, model) {
		model.email = model.email.toLowerCase();
		$.callback(model);
	}
});

NEWACTION('order_price', {
	input: 'email:String, count:Number',
	action: function($, model) {
		$.callback({ email: model.email, price: model.count * 10 });
	}
});
```

```js
exports.install = function() {
	ROUTE('POST /order/', order);
	ROUTE('POST /chain/', chain);
};

function order($) {
	ACTION('order_price', $.body).callback(function(err, response) {
		$.json({ err: err ? err.toString() : null, response: response });
	});
}

async function chain($) {
	var model = await ACTION('order_check', $.body).promise($);
	$.json(await ACTION('order_price', model).promise($));
}
```

Consulta [Acciones](../actions/).

## Módulos, modelos y definiciones

Los archivos de `definitions/` y `modules/` se cargan como antes, y `MAIN`, `FUNC`, `PATH` y `ON('ready')` no cambian.

| Total.js 4 | Total.js 5 |
| --- | --- |
| `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` |
| `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` |
| `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` |
| `CACHE('products')` | `CACHE.read('products')` |

Consulta [Estructura de la aplicación](../application-structure/).

## Pruebas unitarias

`TESTER()` se sustituye por el objeto `Test` de `total5/test`.

Antes:

```js
require('total4');

TESTER(function(group, start) {

	group('Strings', function(test) {

		test('slug()', function(next) {
			next('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug');
		});

		test('capitalize()', function(next) {
			next('total'.capitalize() === 'Total' ? undefined : 'Unexpected value');
		});

	});

	start();
});
```

Después:

```js
require('total5/test');

Test.push('Strings', function(next) {
	Test.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');
	Test.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');
	next();
});

Test.run();
```

Consulta [Pruebas unitarias](../unit-tests/).

## Línea de comandos

| Total.js 4 | Total.js 5 |
| --- | --- |
| `total4 translate` | `total5 translate "$PWD/translate.resource"` |

Indica a `total5 translate` el path completo del archivo de salida. Consulta [Línea de comandos](../command-line/).

## Una aplicación completa

Esta pequeña aplicación de notas tiene una lista pública, escrituras protegidas, una página de inicio, un correo de notificación, un canal WebSocket en directo y un trabajo que se ejecuta cada minuto. Las dos versiones responden a las mismas peticiones de la misma manera, salvo por el título de la página de inicio descrito en [Vistas](#views).

### Total.js 4

`index.js`

```js
const options = {};

options.port = parseInt(process.argv[2]);

var type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';
require('total4/' + type)(options);
```

`config`

```text
name              : Notes
apitoken          : secret
mail_notify       : admin@example.com
mail_from         : notes@example.com
mail_smtp         : 127.0.0.1
mail_smtp_options : { port: 19854 }
maxnotes          : 100
```

`definitions/auth.js`

```js
AUTH(function($) {
	if ($.headers['x-token'] === CONF.apitoken)
		$.success({ id: '1', name: 'Admin' });
	else
		$.invalid();
});
```

`definitions/jobs.js`

```js
MAIN.ticks = 0;

SCHEDULE('* * * * *', function() {
	MAIN.ticks++;
});
```

`schemas/notes.js`

```js
NEWSCHEMA('Notes', function(schema) {

	schema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed');
	schema.define('body', 'String(500)');

	schema.setQuery(function($) {
		NOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback);
	});

	schema.setRead(function($) {
		NOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) {
			if (note)
				$.callback(note);
			else
				$.invalid(404);
		});
	});

	schema.setInsert(function($, model) {
		model.id = UID();
		model.dtcreated = new Date();
		NOSQL('notes').insert(model).callback(function() {
			MAIL(CONF.mail_notify, 'New note', 'mail/note', model);
			MAIN.live && MAIN.live.send({ type: 'note', title: model.title });
			$.success(model.id);
		});
	});

	schema.setRemove(function($) {
		NOSQL('notes').remove().id($.id).callback($.done());
	});

});
```

`controllers/api.js`

```js
exports.install = function() {
	ROUTE('GET     /api/notes/        *Notes --> query');
	ROUTE('GET     /api/notes/{id}/   *Notes --> read');
	ROUTE('+POST   /api/notes/        *Notes --> insert');
	ROUTE('+DELETE /api/notes/{id}/   *Notes --> remove');
	ROUTE('GET     /api/stats/',      stats);
	ROUTE('SOCKET  /live/',           live);
};

function stats() {
	this.json({ ticks: MAIN.ticks });
}

function live() {
	MAIN.live = this;
}
```

`controllers/default.js`

```js
exports.install = function() {
	ROUTE('GET /', index);
};

function index() {
	var self = this;
	self.title('Latest notes');
	NOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) {
		self.view('index', notes);
	});
}
```

`views/layout.html`

```html
<!DOCTYPE html>
<html>
<head>
	@{import('meta')}
</head>
<body>
	@{body}
</body>
</html>
```

`views/index.html`

```html
<h1>@{config.name}</h1>
<ul>
@{foreach note in model}
	<li>@{note.title}</li>
@{end}
</ul>
```

`views/mail/note.html`

```html
<p>New note: @{model.title}</p>
```

### Total.js 5

`definitions/auth.js` y `views/layout.html` siguen igual.

`index.js`

```js
require('total5');

const options = {};

options.port = parseInt(process.argv[2]);
options.release = process.argv.includes('--release');

Total.run(options);
```

`config`

```text
name                : Notes
apitoken            : secret
mail_notify         : admin@example.com
mail_from           : notes@example.com
mail_smtp           : 127.0.0.1
mail_smtp_options   : { port: 19854 }
maxnotes (number)   : 100
```

`definitions/jobs.js`

```js
MAIN.ticks = 0;

CRON('* * * * *', function() {
	MAIN.ticks++;
});
```

`actions/notes.js`

```js
NEWACTION('Notes/query', {
	action: function($) {
		NOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($);
	}
});

NEWACTION('Notes/read', {
	params: '*id:String',
	action: function($) {
		NOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) {
			if (note)
				$.callback(note);
			else
				$.invalid(404);
		});
	}
});

NEWACTION('Notes/insert', {
	input: '*title:String(50), body:String(500)',
	action: function($, model) {

		if (model.title === 'spam') {
			$.invalid('This title is not allowed', 'title');
			return;
		}

		model.id = UID();
		model.dtcreated = new Date();
		NOSQL('notes').insert(model).callback(function() {
			MAIL(CONF.mail_notify, 'New note', 'mail/note', model);
			MAIN.live && MAIN.live.send({ type: 'note', title: model.title });
			$.success(model.id);
		});
	}
});

NEWACTION('Notes/remove', {
	params: '*id:String',
	action: function($) {
		NOSQL('notes').remove().id($.params.id).callback($.done());
	}
});
```

`controllers/api.js`

```js
exports.install = function() {
	ROUTE('GET     /api/notes/        --> Notes/query');
	ROUTE('GET     /api/notes/{id}/   --> Notes/read');
	ROUTE('+POST   /api/notes/        --> Notes/insert');
	ROUTE('+DELETE /api/notes/{id}/   --> Notes/remove');
	ROUTE('GET     /api/stats/',      stats);
	ROUTE('SOCKET  /live/',           live);
};

function stats($) {
	$.json({ ticks: MAIN.ticks });
}

function live($) {
	MAIN.live = $;
}
```

`controllers/default.js`

```js
exports.install = function() {
	ROUTE('GET /', index);
};

function index($) {
	NOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) {
		$.view('index', notes);
	});
}
```

`views/index.html`

```html
@{title('Latest notes')}
<h1>@{config.name}</h1>
<ul>
@{foreach note in model}
	<li>@{note.title}</li>
@{end}
</ul>
```

`views/mail/note.html`

```html
@{layout('')}
<p>New note: @{model.title}</p>
```
