Schemas and actions
Declare schemas with typed and validated fields, write operations and actions, use the $ object and call them from routes and code.
On this page
A schema describes the data your app receives and the operations that work with it. Total.js converts the request body to the types you declare, validates it, and runs your operation with a $ object that knows the model, the query, the user and how to answer. Routes call schemas directly, so a REST endpoint often needs no action of its own.
Put schemas in the schemas/ folder. Total.js loads every file there when the app starts.
Declaring a schema
NEWSCHEMA(name, declaration) creates a schema. The declaration receives the schema and declares its fields and operations:
NEWSCHEMA('Users', function(schema) {
schema.define('id', 'UID');
schema.define('name', 'String(50)', true);
schema.define('email', 'Email', true);
schema.define('age', Number);
schema.define('role', ['admin', 'user']);
schema.setInsert(function($, model) {
model.id = UID();
NOSQL('users').insert(model);
$.success(model.id);
});
});Declaring a schema with an existing name replaces the old one. NEWSCHEMA('Users', null) removes it. GETSCHEMA('Users') returns a declared schema.
Field types
schema.define(name, type, [required], [error]) accepts a constructor, a type name (case does not matter), an array or an object:
| Type | What the value becomes |
|---|---|
String, 'String', 'Text' | A trimmed string. 'String(50)' cuts it to 50 characters |
'Name', 'Capitalize', 'Capitalize2', 'Lower', 'Upper' | A string with its case changed |
'SafeString' | A string checked for XSS and SQL injection |
'Email', 'Phone', 'Zip', 'URL', 'JSON', 'Base64' | A string; a required field must have a valid value |
'Color', 'Icon' | A string with a color or an icon name |
'UID' or UID, 'GUID' or GUID | An identifier |
Number, 'Number', 'Float', 'Decimal', 'Double' | A decimal number |
'Int', 'Integer', 'Byte', 'TinyInt', 'SmallInt' | An integer |
'Number2' | A number; when required, 0 is also valid |
Boolean, 'Boolean', 'Bool' | true or false |
Date, 'Date', 'Time', 'DateTime' | A date |
Object, 'Object' | Any object |
'name:String, age:Number' | An object with these fields |
['a', 'b'] | An enum: one of the values |
{ a: 'A', b: 'B' } | A key-value list: one of the keys |
Array, '[]', '[String]', '[Number]' | An array, of the type in brackets |
'Address', '[Address]' | Another schema, or an array of it, validated with its own rules |
The model your operation receives contains only the declared fields, already converted. A schema without fields passes the body as it came.
Required fields and error messages
The third argument makes a field required. What "required" checks depends on the type:
- a string must not be empty, and
Email,Phone,URL,UIDand similar must be valid; - a number must be greater than
0, and a boolean must betrue; - an array must not be empty.
Instead of true you can pass a function (value, model) that returns true, false or an error message. A string as the third argument makes the field required and is its error message:
schema.define('name', 'String(50)', true);
schema.define('email', 'Email', 'Enter a valid email address');
schema.define('password', 'String(30)', true, 'The password is too short');
schema.define('age', Number, value => value >= 18, 'You must be an adult');Without a message, Total.js reads it from the resource set with schema.setResource() (the key is the field name), or answers The field "name" is invalid. A message that starts with @ is a resource key.
schema.required(name, fn) makes a field required only when fn(model, operations) returns true, for example only on insert.
Default values
schema.define() returns a function that sets the default value. It returns the schema again:
schema.define('count', Number)(10);
schema.define('created', Date)(() => new Date());Classic operations
The classic way gives the schema up to seven operations. Each one receives $ and the validated model:
| Method | Operation name in routes |
|---|---|
schema.setSave(fn) | save |
schema.setInsert(fn) | insert |
schema.setUpdate(fn) | update |
schema.setPatch(fn) | patch |
schema.setRead(fn) | read (or get) |
schema.setQuery(fn) | query (or list) |
schema.setRemove(fn) | remove |
schema.addWorkflow(name, fn) adds an operation with your own name:
NEWSCHEMA('Users', function(schema) {
schema.define('name', 'String(50)', true);
schema.setQuery(function($) {
NOSQL('users').find().callback($.callback);
});
schema.setRead(function($) {
NOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');
});
schema.addWorkflow('activate', function($) {
NOSQL('users').modify({ active: true }).where('id', $.id);
$.success();
});
});Actions: schema.action()
schema.action(name, options) is the newer style. One object declares the operation and everything it needs: the input, the query and the URL parameters it accepts, and who may run it. The input is declared inline, so the schema needs no define():
NEWSCHEMA('Users', function(schema) {
schema.action('list', {
name: 'List of users',
query: 'page:Number, limit:Number',
user: true,
action: function($) {
NOSQL('users').find().take($.query.limit || 20).callback($.callback);
}
});
schema.action('create', {
name: 'Create a user',
input: '*name:String(50), *email:Email, role:{admin|user}',
permissions: 'admin',
action: function($, model) {
model.id = UID();
NOSQL('users').insert(model);
$.success(model.id);
}
});
});In input, query and params, fields are separated by commas, * marks a required field, [String] is an array, {a|b} an enum and @Name another schema or action. Instead of an inline declaration you can give the name of a JSON schema from the jsonschemas/ folder.
| Option | What it does |
|---|---|
action | The function ($, model) that runs the action |
name | A description of the action |
input | Fields of the request body. Invalid data stops the action |
output | Fields of the response. Other fields are removed |
query | Fields of the query string, converted into $.query |
params | Fields of the URL parameters, converted into $.params |
user | true: only for a signed-in user, otherwise 401 |
sa | true: only for a super admin (user.sa or user.su) |
permissions | 'read,write': the user needs one of them in user.permissions or user.roles |
cache | Caches the response: { query, params, user, language, expire } |
Both styles call operations the same way, and you can mix them in one schema.
The $ object
Every operation receives $. It ends the operation and gives you the request:
| Member | What it is |
|---|---|
$.callback(value) | Answers with the value; $.callback(err) with an error |
$.success([value]) | Answers { "success": true, "value": ... } |
$.invalid(name, [message]) | Answers with an error; $.invalid(404) with a status code |
$.done([value]) | Returns a callback (err, response) that answers with success or the error |
$.successful(fn) | Returns a callback that runs fn(response) only when there is no error |
$.redirect(url) | Redirects the request |
$.model | The validated model |
$.query, $.params, $.id | The query string, the URL parameters and the first one of them |
$.user, $.session | The signed-in user and the session |
$.keys | In a PATCH request, the fields that were sent |
$.filter | The query converted with the filter of the operation |
$.controller | The controller; also $.req, $.res, $.headers, $.ip, $.language, $.files, $.body |
Call exactly one of $.callback(), $.success(), $.invalid() or $.redirect() per operation:
schema.setRead(function($) {
NOSQL('users').one().where('id', $.id).callback(function(err, user) {
if (user)
$.callback(user);
else
$.invalid(404);
});
});Calling operations from routes
*Schema --> operation after the URL validates the request body with the schema and runs the operation. The first dynamic parameter becomes $.id:
exports.install = function() {
ROUTE('GET /api/users/ *Users --> query');
ROUTE('GET /api/users/{id}/ *Users --> read');
ROUTE('POST /api/users/ *Users --> insert');
ROUTE('PATCH /api/users/{id}/ *Users --> patch');
ROUTE('DELETE /api/users/{id}/ *Users --> remove');
ROUTE('POST /api/users/{id}/activate/ *Users --> activate');
};GET requests have no body, so there is nothing to validate. In a PATCH request, only the fields that were sent are validated. Several operations run one after another, and (response) after one of them chooses whose result is sent back:
ROUTE('POST /api/users/ *Users --> insert (response) notify');The whole syntax is in the Routing guide.
NEWACTION(): actions without a schema
NEWACTION(name, options) declares an action that does not belong to any schema. It takes the same options as schema.action(). Name actions with a slash, Users/create, to group them:
NEWACTION('Users/create', {
name: 'Create a user',
input: '*name:String(50), *email:Email',
user: true,
action: function($, model) {
model.id = UID();
NOSQL('users').insert(model);
$.success(model.id);
}
});A route calls it with --> and no schema:
ROUTE('POST /api/users/ --> Users/create');The option route: 'API /api/' declares an API route for the action by itself; the API name is the action name in lowercase with _ instead of / (users_create).
Running operations from code
CALL() runs actions and schema operations from anywhere in your code. It starts on the next tick, so you can set options first:
CALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {
// ...
});
var users = await CALL('Users --> list').query({ page: 1 }).promise();Inside an operation, $.action(name, [data]) does the same; a name without --> is an operation of the current schema. EXEC('+Users --> insert', model, callback) also runs schema operations and returns a promise without a callback. MAKE('Users', model) only validates a model.
All the methods are in the Schemas reference.