Migrating from Total.js 4
Move a Total.js 4 application to Total.js 5, area by area, with the code before and after each change.
On this page
This guide moves an application from Total.js 4 to Total.js 5. It lists what you have to change in each area, with the old code next to its replacement, and ends with a small application shown in both versions.
Recommended order of work
- Replace the
total4package withtotal5and update the start script. - Rename the configuration keys and add types to numeric values.
- Turn schemas into actions and update the routes that call them.
- Replace
thiswith$in routes and controllers and in middleware. - Check views and mail views: folders, layouts and titles.
- Update NoSQL queries, RESTBuilder error handling, WebSockets and file storage.
- Replace
SCHEDULE(), operations and tasks, andMODULE()andMODEL()calls. - Rewrite the unit tests and run the application.
Start script
| 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) |
Before:
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);After:
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);Both scripts start in debug mode, and in release mode with node index.js --release. See Installation.
Schemas and actions
schema.define() and the schema.setInsert() family do not exist in Total.js 5. An unchanged schema stops the application at start with TypeError: schema.define is not a function. Move each operation into a NEWACTION() in the actions/ folder and declare its fields 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' and $.params.id |
.callback($.callback) | .callback($) |
$.invalid('age', 'Message') | $.invalid('Message', 'age') |
CALL('Math --> double', data) | ACTION('Math/double', data) |
Before:
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');
};After:
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');
};Custom validators
A validator function in schema.define() moves into the action.
Before:
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);
});
});After:
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);
}
});Schemas that already use schema.action()
These schemas keep working. Only the route changes: *Tags --> list becomes --> 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');
};Values and errors your clients will notice
| Case | Total.js 4 | Total.js 5 |
|---|---|---|
Optional Number is missing | The field is 0 | The field is left out |
| Optional enum is missing | The field is left out | The field is '' |
| Enum value is not in the list | Value dropped, request accepted | 400 with an error for the field |
| Keys of a required-field error | name, error, path, prefix | name, error, path |
Keys of an error from $.invalid() with a field | name, error | error, path |
A client that reads name from your own errors has to read path instead. See Actions and JSON schemas.
Routes
| 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): the method is required |
{page:number} converts the value | {page} is a string: $.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) and UNAUTHORIZED($, 'admin') in the handler |
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') |
A route without a size flag refuses a JSON body above 256 kB with 431, so give routes that import large data their own limit. An unknown API endpoint answers 400 instead of 404. See Routing.
Before:
exports.install = function() {
ROUTE('GET /users/{id}/orders/{order}/', detail);
};
function detail(id, order) {
this.json({ id: id, order: order, params: this.params });
}After:
exports.install = function() {
ROUTE('GET /users/{id}/orders/{order}/', detail);
};
function detail($) {
$.json({ id: $.params.id, order: $.params.order, params: $.params });
}Controllers
Handlers receive the controller as $. this is no longer the controller in HTTP routes.
| 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) |
These members only need this replaced with $: params, query, body, files, headers, url, ip, ua, mobile, robot, xhr, referrer, user, language, cookie(), hostname(), json(), plain(), view(), filefs() and stream(type, stream).
An error route sets the status in the same way:
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');
}See Controller.
Views
The syntax of view files does not change: expressions, conditions, loops, sections, partial views and helpers from DEF.helpers work as before.
| Total.js 4 | Total.js 5 |
|---|---|
this.view('detail') in controllers/users.js finds views/users/detail.html | $.view('users/detail'): the name always starts in views/ |
The layout can read model | Set @{repository.name = model.name} in the view and read repository in the layout |
this.title('Products') | @{title('Products')} in the view |
this.repository.page = 'list' | @{repository.page = 'list'} in the view |
VIEW('mail/order', model) | F.view('mail/order', model), with @{layout('')} in the view |
The title of the home page gets - and CONF.name | The title of the home page stays as you wrote it |
Before:
<title>@{model.name}</title>@{body}After:
<title>@{repository.name}</title>@{body}@{repository.name = model.name}
<h1>@{model.name}</h1>See 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']) | Third argument 'routes', inside ON('ready') |
Before:
MIDDLEWARE('poweredby', function($) {
$.res.setHeader('x-server', 'myapp');
$.next();
});
USE('poweredby', ['web']);After:
ON('ready', function() {
NEWMIDDLEWARE('poweredby', function($, next) {
$.response.headers['x-server'] = 'myapp';
next();
}, 'routes');
});See Middleware.
WebSockets
A SOCKET route keeps its structure, and this still works inside its handler.
| 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) on a text route | client.send(text, true) |
client.close('finished', 4000) | client.close(4000, 'finished') |
A refused +SOCKET client connects and is closed with 4001 | The handshake is refused and the client sees 1006 |
See WebSockets.
NoSQL
Existing .nosql files can be read as they are. insert(), find(), read(), update(), remove(), where(), search(), fields(), skip(), take(), first() and the +field update prefix do not change.
| Total.js 4 | Total.js 5 |
|---|---|
find() starts with the oldest document | find() starts with the newest document: add sort() when the order matters |
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() does not exist in Total.js 5, so move the rows of .table files into a NoSQL database yourself.
Before:
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 });
}After:
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 });
}See NoSQL database.
RESTBuilder
| Total.js 4 | Total.js 5 |
|---|---|
A status of 400 or higher is an error only with .strict() | A status of 400 or higher is always an error |
.callback($.callback) in an operation | .callback($) in an action |
Code that reads output.status after a failed request has to handle err first. See HTTP requests.
Configuration
| 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 is a number | limit (number) : 50: without a type the value is a string |
smtp (object) : { port: 465 } | smtp (json) : { "port": 465 } |
config-release | Not loaded: keep the values in config |
Before:
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 : falseAfter:
name : Shop
$root : /app/
$timezone : Europe/Bratislava
$cookiesamesite : Strict
$cookiesecure : true
$xpoweredby : MyServer
$customtitles : true
$httpcompress : falseCORS(), name, (array) values and mail_smtp_options written as a JavaScript object work as before. See Configuration.
Authorization
The AUTH() delegate, the + and - route flags and UNAUTHORIZED() do not change. SESSION() does not exist in Total.js 5: use the built-in session of AUTH().
| Total.js 4 | Total.js 5 |
|---|---|
SESSION() with ondata | AUTH(opt) with opt.onread |
session.setcookie($, options, callback) | opt.authcookie($, UID(), userid, '1 hour') |
session.remove2(userid) and clearing the cookie | opt.logout($) in an action |
Before:
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;After:
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() removes the session from memory and clears the cookie. A saved copy of the token is signed, so it is accepted again whenever onread returns a user. Check the session in your database inside onread when signing out has to revoke the token. See Authorization.
Localization
Resource files and @(Text) in views stay the same, and the generated keys are identical.
| 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)') |
See Localization.
| Total.js 4 | Total.js 5 |
|---|---|
MAIL() renders the view without a layout | MAIL() renders the view into views/layout.html |
ON('mail', fn) | ON('$mail', fn) |
message.address_to | message.email_to |
Start every mail view with @{layout('')}. Without it the message is wrapped in your site layout, and when views/layout.html does not exist the message is not sent at all.
Before:
<p>Hello @{model.name}</p>After:
@{layout('')}
<p>Hello @{model.name}</p>See Sending email.
File storage
The arguments of save() change order: the custom data now comes before the callback.
| Total.js 4 | Total.js 5 |
|---|---|
fs.save(id, name, data, callback, custom) | fs.save(id, name, data, custom, callback) |
read() and $.filefs() do not change. See File storage.
Scheduling
| Total.js 4 | Total.js 5 |
|---|---|
SCHEDULE('* * * * *', fn) | CRON('* * * * *', fn) |
SCHEDULE('03:00', '1 day', fn) | CRON('0 3 * * *', fn) |
Before:
MAIN.runs = 0;
SCHEDULE('* * * * *', function() {
MAIN.runs++;
});After:
MAIN.runs = 0;
CRON('* * * * *', function() {
MAIN.runs++;
});Operations and tasks
NEWOPERATION(), OPERATION(), RUN(), NEWTASK() and TASK() do not exist in Total.js 5. Each operation becomes an action, and the steps of a task become one action or several actions called in sequence.
| 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($) for each step |
NEWTASK('order', fn) and TASK('order/check', ...) | NEWACTION('order', { action: fn }) |
Before:
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);
});
}After:
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($));
}See Actions.
Modules, models and definitions
Files in definitions/ and modules/ load as before, and MAIN, FUNC, PATH and ON('ready') do not change.
| 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') |
Unit tests
TESTER() is replaced by the Test object of total5/test.
Before:
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();
});After:
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();See Unit tests.
Command line
| Total.js 4 | Total.js 5 |
|---|---|
total4 translate | total5 translate "$PWD/translate.resource" |
Give total5 translate the full path of the output file. See Command line.
A complete application
This small notes application has a public list, protected writes, a home page, a notification mail, a live WebSocket channel and a job that runs every minute. Both versions answer the same requests in the same way, except for the home page title described in Views.
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 and views/layout.html stay the same.
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>