Migrazione da Total.js 4
Porta un'applicazione Total.js 4 a Total.js 5, area per area, con il codice prima e dopo ogni modifica.
In questa pagina
Questa guida porta un'applicazione da Total.js 4 a Total.js 5. Elenca cosa devi cambiare in ogni area, con il vecchio codice accanto al suo sostituto, e si chiude con una piccola applicazione mostrata in entrambe le versioni.
Ordine di lavoro consigliato
- Sostituisci il pacchetto
total4contotal5e aggiorna lo script di avvio. - Rinomina le chiavi di configurazione e aggiungi i tipi ai valori numerici.
- Trasforma gli schemi in azioni e aggiorna le route che li richiamano.
- Sostituisci
thiscon$nelle route e nei controller e nel middleware. - Controlla le viste e le viste delle email: cartelle, layout e titoli.
- Aggiorna le query NoSQL, la gestione degli errori di RESTBuilder, i WebSocket e l'archiviazione dei file.
- Sostituisci
SCHEDULE(), le operazioni e i task e le chiamate aMODULE()eMODEL(). - Riscrivi i test unitari e avvia l'applicazione.
Script di avvio
| 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) |
Prima:
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);Dopo:
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);Entrambi gli script si avviano in modalità debug e, con node index.js --release, in modalità release. Vedi Installazione.
Schemi e azioni
schema.define() e la famiglia di schema.setInsert() non esistono in Total.js 5. Uno schema non modificato blocca l'applicazione all'avvio con TypeError: schema.define is not a function. Sposta ogni operazione in un NEWACTION() nella cartella actions/ e dichiara i suoi campi in 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' e $.params.id |
.callback($.callback) | .callback($) |
$.invalid('age', 'Message') | $.invalid('Message', 'age') |
CALL('Math --> double', data) | ACTION('Math/double', data) |
Prima:
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);
});
});exports.install = function() {
ROUTE('POST /api/users/ *Users --> insert');
};Dopo:
NEWACTION('Users/insert', {
input: '*name:String(30), *email:Email, age:Number, role:{admin|user}',
action: function($, model) {
model.id = 'A1';
$.success(model);
}
});exports.install = function() {
ROUTE('POST /api/users/ --> Users/insert');
};Validatori personalizzati
Una funzione di validazione in schema.define() si sposta nell'azione.
Prima:
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);
});
});Dopo:
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);
}
});Schemi che usano già schema.action()
Questi schemi continuano a funzionare. Cambia solo la route: *Tags --> list diventa --> Tags/list.
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);
}
});
});exports.install = function() {
ROUTE('GET /api/tags/ --> Tags/list');
ROUTE('POST /api/tags/ --> Tags/create');
};Valori ed errori che i tuoi client noteranno
| Caso | Total.js 4 | Total.js 5 |
|---|---|---|
Number opzionale assente | Il campo è 0 | Il campo viene omesso |
| Enum opzionale assente | Il campo viene omesso | Il campo è '' |
| Valore enum non presente nell'elenco | Valore scartato, richiesta accettata | 400 con un errore per il campo |
| Chiavi di un errore di campo obbligatorio | name, error, path, prefix | name, error, path |
Chiavi di un errore di $.invalid() con un campo | name, error | error, path |
Un client che legge name dai tuoi errori deve leggere invece path. Vedi Azioni e Schemi JSON.
Route
| 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): il metodo è obbligatorio |
{page:number} converte il valore | {page} è una stringa: $.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) e UNAUTHORIZED($, 'admin') nel gestore |
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 route senza flag di dimensione rifiuta con 431 un corpo JSON superiore a 256 kB, quindi assegna un limite proprio alle route che importano grandi quantità di dati. Un endpoint API sconosciuto risponde 400 invece di 404. Vedi Routing.
Prima:
exports.install = function() {
ROUTE('GET /users/{id}/orders/{order}/', detail);
};
function detail(id, order) {
this.json({ id: id, order: order, params: this.params });
}Dopo:
exports.install = function() {
ROUTE('GET /users/{id}/orders/{order}/', detail);
};
function detail($) {
$.json({ id: $.params.id, order: $.params.order, params: $.params });
}Controller
I gestori ricevono il controller come $. Nelle route HTTP this non è più il controller.
| 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) |
Per questi membri basta sostituire this con $: params, query, body, files, headers, url, ip, ua, mobile, robot, xhr, referrer, user, language, cookie(), hostname(), json(), plain(), view(), filefs() e stream(type, stream).
Una route di errore imposta lo stato allo stesso modo:
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');
}Vedi Controller.
Viste
La sintassi dei file di vista non cambia: espressioni, condizioni, cicli, sezioni, viste parziali e helper di DEF.helpers funzionano come prima.
| Total.js 4 | Total.js 5 |
|---|---|
this.view('detail') in controllers/users.js trova views/users/detail.html | $.view('users/detail'): il nome parte sempre da views/ |
Il layout può leggere model | Imposta @{repository.name = model.name} nella vista e leggi repository nel layout |
this.title('Products') | @{title('Products')} nella vista |
this.repository.page = 'list' | @{repository.page = 'list'} nella vista |
VIEW('mail/order', model) | F.view('mail/order', model), con @{layout('')} nella vista |
Al titolo della home page vengono aggiunti - e CONF.name | Il titolo della home page resta come l'hai scritto |
Prima:
<title>@{model.name}</title>@{body}Dopo:
<title>@{repository.name}</title>@{body}@{repository.name = model.name}
<h1>@{model.name}</h1>Vedi Viste.
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']) | Terzo argomento 'routes', dentro ON('ready') |
Prima:
MIDDLEWARE('poweredby', function($) {
$.res.setHeader('x-server', 'myapp');
$.next();
});
USE('poweredby', ['web']);Dopo:
ON('ready', function() {
NEWMIDDLEWARE('poweredby', function($, next) {
$.response.headers['x-server'] = 'myapp';
next();
}, 'routes');
});Vedi Middleware.
WebSocket
Una route SOCKET mantiene la sua struttura e this continua a funzionare nel suo gestore.
| 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) su una route di testo | client.send(text, true) |
client.close('finished', 4000) | client.close(4000, 'finished') |
Un client +SOCKET rifiutato si connette e viene chiuso con 4001 | L'handshake viene rifiutato e il client riceve 1006 |
Vedi WebSocket.
NoSQL
I file .nosql esistenti si possono leggere così come sono. insert(), find(), read(), update(), remove(), where(), search(), fields(), skip(), take(), first() e il prefisso di aggiornamento +field non cambiano.
| Total.js 4 | Total.js 5 |
|---|---|
find() parte dal documento più vecchio | find() parte dal documento più recente: aggiungi sort() quando l'ordine è importante |
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() non esiste in Total.js 5, quindi devi spostare tu stesso le righe dei file .table in un database NoSQL.
Prima:
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 });
}Dopo:
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 });
}Vedi Database NoSQL.
RESTBuilder
| Total.js 4 | Total.js 5 |
|---|---|
Uno stato 400 o superiore è un errore solo con .strict() | Uno stato 400 o superiore è sempre un errore |
.callback($.callback) in un'operazione | .callback($) in un'azione |
Il codice che legge output.status dopo una richiesta non riuscita deve prima gestire err. Vedi Richieste HTTP.
Configurazione
| 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 è un numero | limit (number) : 50: senza tipo il valore è una stringa |
smtp (object) : { port: 465 } | smtp (json) : { "port": 465 } |
config-release | Non viene caricato: tieni i valori in config |
Prima:
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 : falseDopo:
name : Shop
$root : /app/
$timezone : Europe/Bratislava
$cookiesamesite : Strict
$cookiesecure : true
$xpoweredby : MyServer
$customtitles : true
$httpcompress : falseCORS(), name, i valori (array) e mail_smtp_options scritto come oggetto JavaScript funzionano come prima. Vedi Configurazione.
Autorizzazione
Il delegate AUTH(), i flag di route + e - e UNAUTHORIZED() non cambiano. SESSION() non esiste in Total.js 5: usa la sessione integrata di 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) e cancellazione del cookie | opt.logout($) in un'azione |
Prima:
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;Dopo:
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;NEWACTION('Account/logout', {
action: function($) {
MAIN.session.logout($);
$.success();
}
});opt.logout() rimuove la sessione dalla memoria e cancella il cookie. Una copia salvata del token è firmata, quindi viene accettata di nuovo ogni volta che onread restituisce un utente. Se il logout deve revocare il token, controlla la sessione nel tuo database dentro onread. Vedi Autorizzazione.
Localizzazione
I file di risorse e @(Text) nelle viste restano invariati e le chiavi generate sono identiche.
| 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)') |
Vedi Localizzazione.
| Total.js 4 | Total.js 5 |
|---|---|
MAIL() esegue il rendering della vista senza layout | MAIL() esegue il rendering della vista dentro views/layout.html |
ON('mail', fn) | ON('$mail', fn) |
message.address_to | message.email_to |
Inizia ogni vista email con @{layout('')}. Senza, il messaggio viene inserito nel layout del tuo sito e, se views/layout.html non esiste, il messaggio non viene inviato affatto.
Prima:
<p>Hello @{model.name}</p>Dopo:
@{layout('')}
<p>Hello @{model.name}</p>Vedi Invio di email.
Archiviazione dei file
Gli argomenti di save() cambiano ordine: i dati personalizzati ora vengono prima della callback.
| Total.js 4 | Total.js 5 |
|---|---|
fs.save(id, name, data, callback, custom) | fs.save(id, name, data, custom, callback) |
read() e $.filefs() non cambiano. Vedi Archiviazione dei file.
Pianificazione
| Total.js 4 | Total.js 5 |
|---|---|
SCHEDULE('* * * * *', fn) | CRON('* * * * *', fn) |
SCHEDULE('03:00', '1 day', fn) | CRON('0 3 * * *', fn) |
Prima:
MAIN.runs = 0;
SCHEDULE('* * * * *', function() {
MAIN.runs++;
});Dopo:
MAIN.runs = 0;
CRON('* * * * *', function() {
MAIN.runs++;
});Vedi Pianificazione ed eventi.
Operazioni e task
NEWOPERATION(), OPERATION(), RUN(), NEWTASK() e TASK() non esistono in Total.js 5. Ogni operazione diventa un'azione e i passaggi di un task diventano un'azione o più azioni richiamate in sequenza.
| 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($) per ogni passaggio |
NEWTASK('order', fn) e TASK('order/check', ...) | NEWACTION('order', { action: fn }) |
Prima:
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);
});
}Dopo:
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 });
}
});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($));
}Vedi Azioni.
Moduli, modelli e definizioni
I file in definitions/ e modules/ si caricano come prima, e MAIN, FUNC, PATH e ON('ready') non cambiano.
| 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') |
Vedi Struttura dell'applicazione.
Test unitari
TESTER() viene sostituito dall'oggetto Test di total5/test.
Prima:
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();
});Dopo:
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();Vedi Test unitari.
Riga di comando
| Total.js 4 | Total.js 5 |
|---|---|
total4 translate | total5 translate "$PWD/translate.resource" |
Passa a total5 translate il path completo del file di output. Vedi Riga di comando.
Un'applicazione completa
Questa piccola applicazione di note ha un elenco pubblico, scritture protette, una home page, un'email di notifica, un canale WebSocket in tempo reale e un job eseguito ogni minuto. Entrambe le versioni rispondono alle stesse richieste allo stesso modo, tranne che per il titolo della home page descritto in Viste.
Total.js 4
index.js
const options = {};
options.port = parseInt(process.argv[2]);
var type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';
require('total4/' + type)(options);config
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 : 100definitions/auth.js
AUTH(function($) {
if ($.headers['x-token'] === CONF.apitoken)
$.success({ id: '1', name: 'Admin' });
else
$.invalid();
});definitions/jobs.js
MAIN.ticks = 0;
SCHEDULE('* * * * *', function() {
MAIN.ticks++;
});schemas/notes.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
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
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
<!DOCTYPE html>
<html>
<head>
@{import('meta')}
</head>
<body>
@{body}
</body>
</html>views/index.html
<h1>@{config.name}</h1>
<ul>
@{foreach note in model}
<li>@{note.title}</li>
@{end}
</ul>views/mail/note.html
<p>New note: @{model.title}</p>Total.js 5
definitions/auth.js e views/layout.html restano invariati.
index.js
require('total5');
const options = {};
options.port = parseInt(process.argv[2]);
options.release = process.argv.includes('--release');
Total.run(options);config
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) : 100definitions/jobs.js
MAIN.ticks = 0;
CRON('* * * * *', function() {
MAIN.ticks++;
});actions/notes.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
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
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
@{title('Latest notes')}
<h1>@{config.name}</h1>
<ul>
@{foreach note in model}
<li>@{note.title}</li>
@{end}
</ul>views/mail/note.html
@{layout('')}
<p>New note: @{model.title}</p>