Schemas
NEWSCHEMA(), schema methods, the $ object of operations, NEWACTION() and how to run operations from code.
On this page
A schema is declared with NEWSCHEMA(), usually in a file of the schemas/ folder; actions without a schema with NEWACTION(). Every operation receives the $ object. The guide Schemas and actions explains how the parts work together; this page is the exact reference.
API
method
NEWSCHEMA(name, [declaration])
Declares a schema: its fields, validation and operations.
NEWSCHEMA(name, [declaration])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the schema, used in routes (*Users) and in CALL(). |
declaration? |
Function |
function(schema) that declares fields and operations, or null to remove the schema. |
Returns SchemaBuilderEntity The new schema (nothing when it is removed).
The declaration runs at once with the schema as its argument and as this. A schema with the same name is replaced. Pass null as the declaration to remove a schema. With a function as the only argument, the schema gets a random name (dynamic schema).
NEWSCHEMA('Users', function(schema) {
schema.define('name', 'String(50)', true);
schema.define('email', 'Email', true);
schema.setInsert(function($, model) {
model.id = UID();
NOSQL('users').insert(model);
$.success(model.id);
});
});
NEWSCHEMA('Users', null);
method
GETSCHEMA(name, [callback], [timeout])
Returns a declared schema.
GETSCHEMA(name, [callback], [timeout])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the schema. |
callback? |
Function |
function(err, schema), called when the schema exists. |
timeout? |
Number |
How long to wait, in milliseconds. Default: 20000 |
Returns SchemaBuilderEntity The schema, or undefined. Nothing when a callback is given.
With a callback, it waits until the schema is declared (20 seconds by default) and calls callback(err, schema).
var schema = GETSCHEMA('Users');
console.log(schema.fields);
method
schema.define(name, type, [required], [error], [xss])
Declares a field: its type, whether it is required and its error message.
schema.define(name, type, [required], [error], [xss])| Parameter | Type | Description |
|---|---|---|
name |
String|Array |
Name of the field, or an array of names. |
type |
Function|String|Array|Object |
Type of the field (see above), or null to remove it. |
required? |
Boolean|Function|String |
true; a function (value, model) that returns true, false or an error message; or an error message, which also makes the field required. Default: false |
error? |
String |
Error message when the field is invalid. @key reads a resource. |
xss? |
Boolean|Number |
For strings: true empties a value with XSS or SQL injection, 1 checks only XSS, 2 only SQL injection. |
Returns Function function(value) that sets the default value (a value or a function) and returns the schema.
Types: String, 'String(length)', 'Text', 'SafeString', 'Name', 'Capitalize', 'Capitalize2', 'Lower', 'Upper', 'Email', 'Phone', 'Zip', 'URL', 'JSON', 'Base64', 'Color', 'Icon', 'UID'/UID, 'GUID'/GUID, Number ('Float', 'Decimal', 'Double'), 'Int'/'Integer', 'Byte'/'TinyInt', 'SmallInt', 'Number2', Boolean, Date ('Time', 'DateTime'), Object, an inline object 'name:String, age:Number', an enum ['a', 'b'], a key-value object, Array or '[Type]', and the name of another schema ('Address', '[Address]').
A required field must not be empty: a string must have characters (and a valid value for Email, URL, UID and similar), a number must be greater than 0, a boolean true and an array must have items. A field of another schema is always validated.
The function it returns sets the default value and returns the schema. type null removes the field. An array of names declares several fields with the same type.
schema.define('id', 'UID');
schema.define('name', 'String(50)', true);
schema.define('email', 'Email', 'Enter a valid email address');
schema.define('age', Number, value => value >= 18, 'You must be an adult');
schema.define('role', ['admin', 'user'], true);
schema.define('tags', '[String]');
schema.define('address', 'Address');
schema.define('count', Number)(10);
schema.define('created', Date)(() => new Date());
method
schema.required(name, [fn])
Makes a declared field required, always or only when a condition holds.
schema.required(name, [fn])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the field, or several names separated by commas. |
fn? |
Function|Boolean |
function(model, operations) that returns true when the field must be validated; or false to make the field optional. |
Returns SchemaBuilderEntity The schema, for chaining.
fn(model, operations) decides at each validation whether the field is validated. operations is an object with the names of the operations the route runs, so operations.insert is true on insert. false instead of a function makes the field optional again. Several names can be separated by commas. The field must be declared first.
schema.define('password', 'String(30)');
schema.required('password', (model, operations) => !!operations.insert);
method
schema.undefine(name)
since 0.0.46
Removes a declared field.
schema.undefine(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the field. |
Returns SchemaBuilderEntity The schema, for chaining.
schema.inherit('Users');
schema.undefine('password');
method
schema.inherit(name)
Copies fields, operations and settings of another schema.
schema.inherit(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the schema to inherit from. |
Returns SchemaBuilderEntity The schema, for chaining.
It waits until the other schema is declared. Fields and operations the schema already has are kept.
NEWSCHEMA('Admins', function(schema) {
schema.inherit('Users');
schema.define('level', Number);
});
method
schema.array()
since 0.0.63
The schema receives an array of items instead of one object.
schema.array()Returns SchemaBuilderEntity The schema, for chaining.
Every item is converted and validated. Data that is not an array becomes an empty array.
NEWSCHEMA('Products', function(schema) {
schema.array();
schema.define('id', 'UID', true);
schema.define('count', Number, true);
});
method
schema.action(name, options)
since 0.0.67
Declares an operation with its input, query, parameters and permissions in one object.
schema.action(name, options)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the operation, optionally with URL parameters (read/{id:UID}). It can be left out when options has id or name. |
options |
Object |
Options of the action (see the table). |
Returns SchemaBuilderEntity The schema, for chaining.
input, query, params and output take an inline declaration ('*name:String(50), email:Email, tags:[String], role:{admin|user}'; * is required, @Name is another schema or action) or the name of a JSON schema from jsonschemas/. Invalid data stops the action with an error. A name like 'read/{id:UID}' declares params from the name.
Options:
| Option | What it does |
|---|---|
action | function($, model): the action. It runs with the schema as this |
name | A description |
input | Fields of the request body; the result is in model |
output | Fields of the response |
query | Fields of the query string, in $.query (filter is an alias) |
params | Fields of the URL parameters, in $.params |
user | true: only a signed-in user, otherwise 401 |
sa | true: only a user with sa or su |
permissions | A string or array; the user needs one of them in user.permissions or user.roles (sa/su always pass) |
cache | Caches the response: { query, params, user, language, expire }; true or a list of field names chooses what makes the cache key, expire defaults to '5 minutes' |
publish | Publishes the input or output to TMS |
A route calls the action like any other operation: *Users --> create.
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);
}
});
});
ROUTE('GET /api/users/ *Users --> list');
ROUTE('POST /api/users/ *Users --> create');
schema.action('stats', {
query: 'year:Number',
cache: { query: true, expire: '10 minutes' },
action: function($) {
// ...
}
});
method
schema.setSave(fn, [filter])
Sets the save operation.
schema.setSave(fn, [filter])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The operation, function($, model). It runs with the schema as this. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
Use it when one operation both creates and updates. A route calls it with *Schema --> save; from code use CALL('Schema --> save').
schema.setSave(function($, model) {
if (model.id)
NOSQL('users').modify(model).where('id', model.id);
else {
model.id = UID();
NOSQL('users').insert(model);
}
$.success(model.id);
});
// ROUTE('POST /api/users/ *Users --> save');
method
schema.setInsert(fn, [filter])
Sets the insert operation.
schema.setInsert(fn, [filter])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The operation, function($, model). It runs with the schema as this. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
The model is validated before the operation runs. A route calls it with *Schema --> insert; from code use CALL('Schema --> insert').
schema.setInsert(function($, model) {
model.id = UID();
NOSQL('users').insert(model);
$.success(model.id);
});
// ROUTE('POST /api/users/ *Users --> insert');
method
schema.setUpdate(fn, [filter])
Sets the update operation.
schema.setUpdate(fn, [filter])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The operation, function($, model). It runs with the schema as this. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
The whole model is validated; the id usually comes from the URL in $.id. A route calls it with *Schema --> update; from code use CALL('Schema --> update').
schema.setUpdate(function($, model) {
NOSQL('users').modify(model).where('id', $.id);
$.success();
});
// ROUTE('PUT /api/users/{id}/ *Users --> update');
method
schema.setPatch(fn, [filter])
Sets the patch operation, which changes only the fields that were sent.
schema.setPatch(fn, [filter])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The operation, function($, model). It runs with the schema as this. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
Only the sent fields are converted and validated, and their names are in $.keys. A route calls it with *Schema --> patch; from code use CALL('Schema --> patch').
schema.setPatch(function($, model) {
NOSQL('users').modify(model).where('id', $.id);
$.success();
});
// ROUTE('PATCH /api/users/{id}/ *Users --> patch');
method
schema.setRead(fn, [filter])
Sets the read operation. schema.setGet() is an alias.
schema.setRead(fn, [filter])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The operation, function($, model). It runs with the schema as this. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
A route calls it with *Schema --> read or --> get.
schema.setRead(function($) {
NOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');
});
// ROUTE('GET /api/users/{id}/ *Users --> read');
method
schema.setQuery(fn, [filter])
Sets the query operation, which lists items. schema.setList() is an alias.
schema.setQuery(fn, [filter])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The operation, function($, model). It runs with the schema as this. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
A route calls it with *Schema --> query or --> list. The filter converts the query string into $.filter.
schema.setQuery(function($) {
var filter = $.filter;
NOSQL('users').find().take(filter.limit || 20).skip(((filter.page || 1) - 1) * (filter.limit || 20)).callback($.callback);
}, 'page:Number, limit:Number');
// ROUTE('GET /api/users/ *Users --> query');
method
schema.setRemove(fn, [filter])
Sets the remove operation.
schema.setRemove(fn, [filter])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
The operation, function($, model). It runs with the schema as this. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
A route calls it with *Schema --> remove; from code use CALL('Schema --> remove').
schema.setRemove(function($) {
NOSQL('users').remove().where('id', $.id);
$.success();
});
// ROUTE('DELETE /api/users/{id}/ *Users --> remove');
method
schema.addWorkflow(name, fn, [filter])
Adds an operation with your own name. schema.add() is an alias.
schema.addWorkflow(name, fn, [filter])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the operation. |
fn |
Function|String |
function($, model), or 'Schema --> name'. |
filter? |
String |
Fields of the query string, for example 'page:Number, limit:Number'. The operation reads them converted in $.filter. |
Returns SchemaBuilderEntity The schema, for chaining.
Instead of a function you can give 'Schema --> name' to reuse an operation of another schema.
schema.addWorkflow('activate', function($) {
NOSQL('users').modify({ active: true }).where('id', $.id);
$.success();
});
// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');
schema.addWorkflow('check', 'Common --> check');
method
schema.middleware(fn)
Adds a function that runs before every operation of the schema.
schema.middleware(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, next). |
Returns SchemaBuilderEntity The schema, for chaining.
Call next() to continue. next(true) stops, so the middleware must answer itself, for example with $.invalid(). Several middleware run in the order they were added.
schema.middleware(function($, next) {
if ($.user)
next();
else {
$.invalid(401);
next(true);
}
});
method
schema.setResource(name)
Sets the resource file with the error messages of the schema.
schema.setResource(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the resource file in resources/. |
Returns SchemaBuilderEntity The schema, for chaining.
A field without its own message reads the key with its name from this resource. schema.setPrefix(prefix) adds a prefix to the keys.
schema.setResource('errors');
schema.setPrefix('user_');
schema.define('email', 'Email', true); // key: user_email
method
schema.setTimer(fn)
since 0.0.63
Sets a function that runs every minute. schema.setService() is an alias.
schema.setTimer(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(counter); counter counts the minutes. |
Returns SchemaBuilderEntity The schema, for chaining.
schema.setTimer(function(counter) {
if (counter % 60 === 0)
NOSQL('sessions').remove().where('expire', '<', NOW);
});
method
schema.setDestroy(fn)
since 0.0.63
Sets a function that runs when the schema is removed or replaced.
schema.setDestroy(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(). |
Returns SchemaBuilderEntity The schema, for chaining.
schema.setDestroy(function() {
clearInterval(timer);
});
method
$.callback([value])
Ends the operation and answers with a value or an error.
$.callback([value])| Parameter | Type | Description |
|---|---|---|
value? |
Object|Error |
The response, or an error. |
An Error or an ErrorBuilder answers with that error. $.callback(err, value) also works, so you can pass $.callback to functions that call back with (err, response). In a schema operation, $.callback() without a value answers with the model.
schema.setQuery(function($) {
NOSQL('users').find().callback($.callback);
});
method
$.success([success], [value])
Ends the operation and answers { "success": true, "value": ... }.
$.success([success], [value])| Parameter | Type | Description |
|---|---|---|
success? |
Boolean |
The result. Default: true |
value? |
Object |
A value sent as value. |
Returns SchemaOptions $.
With one argument that is not a boolean, it is the value. $.success(false) answers { "success": false }.
$.success(model.id);
// { "success": true, "value": "1fd0b001ez51d" }
method
$.invalid(name, [message])
Ends the operation with an error.
$.invalid(name, [message])| Parameter | Type | Description |
|---|---|---|
name |
String|Number|Error |
Name of the field, a message, a status code or an error. |
message? |
String |
The error message. @key reads a resource. |
Returns SchemaOptions|Function $, or a callback when called without arguments.
$.invalid('email') reports an invalid field with its default message, $.invalid('email', 'Wrong email') with your message, $.invalid('Something went wrong') a message without a field and $.invalid(404) a status code. An Error or ErrorBuilder is also accepted. Without arguments it returns a function (err) that ends the operation with that error.
schema.setRead(function($) {
NOSQL('users').one().where('id', $.id).callback(function(err, user) {
if (err)
$.invalid(err);
else if (!user)
$.invalid(404);
else
$.callback(user);
});
});
method
$.done([value])
Returns a callback (err, response) that ends the operation with success or with the error.
$.done([value])| Parameter | Type | Description |
|---|---|---|
value? |
Boolean|Object |
true to send the response, or a value to send. |
Returns Function function(err, response).
$.done() answers { "success": true }, $.done(true) puts the response in value and $.done(something) puts something in value.
schema.setRemove(function($) {
NOSQL('users').remove().where('id', $.id).callback($.done());
});
method
$.successful(fn)
Returns a callback that ends the operation on an error and otherwise runs fn.
$.successful(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(response), run with $ as this. |
Returns Function function(err, response).
NOSQL('users').one().where('id', $.id).callback($.successful(function(user) {
$.callback(user || {});
}));
method
$.promisify(fn, [a], [b], [c])
since 0.0.97
Runs a function with a Node.js style callback and returns a promise.
$.promisify(fn, [a], [b], [c])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
A function whose last argument is callback(err, response). |
a, b, c? |
Object |
Arguments for fn. |
Returns Promise Resolves with the response.
The arguments are passed to fn before the callback. On an error, the operation ends with it and the promise never resolves.
schema.action('read', {
action: async function($) {
var data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));
$.callback(data.toString('utf8').parseJSON());
}
});
method
$.redirect(url)
Ends the operation and redirects the request to another URL.
$.redirect(url)| Parameter | Type | Description |
|---|---|---|
url |
String |
The target URL. |
Returns SchemaOptions $.
$.redirect('/login/');
method
$.action(name, [model])
Runs another action or operation from inside an operation, with the same controller.
$.action(name, [model])| Parameter | Type | Description |
|---|---|---|
name |
String |
Operation of this schema, Schema --> operation or an action name. |
model? |
Object |
Data for the operation. |
Returns SchemaCall The same object as CALL().
A name without --> is an operation of the current schema. A +, - or # prefix sets the method (POST, GET or PATCH). It is CALL() bound to the current request, so it returns the same object with .callback() and .promise().
schema.action('create', {
input: '*name:String',
action: async function($, model) {
var user = await $.action('-read').promise($);
// ...
}
});
method
$.on(name, fn)
since 0.0.63
Listens to an event of the operation: error, response or end.
$.on(name, fn)| Parameter | Type | Description |
|---|---|---|
name |
String |
error, response or end. |
fn |
Function |
The listener. |
Returns SchemaOptions $.
error gets the errors, response the response and end both (err, response). They fire when a schema operation called with a single operation ends.
$.on('end', function(err, response) {
console.log('done', err, response);
});
property
$.model
The validated model of the operation.
$.modelReturns Object
It contains only the declared fields, converted to their types. Operations also get it as the second argument. $.value is an alias.
schema.setInsert(function($) {
console.log($.model.name);
$.success();
});
property
$.query
The query string of the request.
$.queryReturns Object
In an action with the query option, the fields are converted and validated.
// GET /api/users/?page=2
var page = $.query.page;
property
$.params
The dynamic parameters of the route URL.
$.paramsReturns Object
In an action with the params option, they are converted and validated.
// ROUTE('GET /api/users/{id}/ *Users --> read');
var id = $.params.id;
property
$.id
The first dynamic parameter of the route URL, usually the id.
$.idReturns String
// ROUTE('GET /api/users/{id}/ *Users --> read');
NOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');
property
$.user
The signed-in user of the request, or null.
$.userReturns Object
Actions with user, sa or permissions check it before they run. $.session holds the session.
model.userid = $.user.id;
property
$.keys
In a PATCH request, the names of the fields that were sent; otherwise null.
$.keysReturns Array
Only these fields are converted and validated.
schema.setPatch(function($, model) {
console.log($.keys); // ['name']
NOSQL('users').modify(model).where('id', $.id);
$.success();
});
property
$.filter
The query string converted with the filter of the operation.
$.filterReturns Object
The filter is the second argument of schema.setQuery() and the other set methods. Without a filter it is the query as it came.
schema.setQuery(function($) {
console.log($.filter.page); // a number
$.callback([]);
}, 'page:Number, limit:Number');
property
$.controller
The controller of the request, or nothing when the operation runs from code.
$.controllerReturns Controller
$ also reads some properties of the controller directly: $.req, $.res, $.headers, $.ip, $.ua, $.language, $.files, $.body, $.url, $.path, $.mobile and $.sessionid.
console.log($.ip, $.language, $.headers['user-agent']);
property
$.responses
The responses of the previous operations when a route or CALL() runs several of them.
$.responsesReturns Object
$.response(name) returns one of them.
// ROUTE('POST /api/orders/ *Orders --> check insert');
schema.setInsert(function($, model) {
var check = $.response('check');
// ...
});
method
NEWACTION(name, options)
since 0.0.81
Declares an action that does not belong to a schema.
NEWACTION(name, options)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the action, for example Users/create. It can be left out when options has id or name. |
options |
Object |
Options of the action. |
Returns Object The action, with a remove() method.
It takes the same options as schema.action() (action, name, input, output, query, params, user, sa, permissions, cache, publish) and also:
| Option | What it does |
|---|---|
route | 'API /api/' declares an API route for the action. The API name is the action name in lowercase with _ instead of /, with + when the action has input and - otherwise |
csrf, encrypt, compress | Like schema.csrf(), schema.encrypt() and schema.compress() |
The action runs with $ as this. Declaring an action with an existing name replaces it, and action.remove() removes it with its route. A route calls an action with --> and no schema.
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);
}
});
ROUTE('POST /api/users/ --> Users/create');
NEWACTION('Users/list', {
query: 'page:Number',
route: 'API /api/',
action: function($) {
NOSQL('users').find().callback($.callback);
}
});
// the client calls POST /api/ with { "schema": "users_list" }
method
CALL(name, [model], [controller])
since 0.0.67
Runs actions or schema operations from code.
CALL(name, [model], [controller])| Parameter | Type | Description |
|---|---|---|
name |
String |
Action name or Schema --> operations, optionally with a +, - or # prefix. |
model? |
Object |
Data for the operation. It is validated. |
controller? |
Controller|SchemaOptions |
The request to run with, or a $. |
Returns SchemaCall An object with the methods in the table.
name is an action (Users/create), several actions separated by spaces, or Schema --> operations. A +, - or # prefix sets the method (POST, GET or PATCH); without it, the call is POST when there is a model. The call starts on the next tick, so set its options first:
| Method | What it sets |
|---|---|
.query(obj), .params(obj) | $.query and $.params |
.user(obj), .language(str) | $.user (or the user of a $) and the language |
.controller(ctrl) | The controller (or the controller of a $) |
.callback(fn) | function(err, response) |
.done($, fn) | Ends $ on an error, otherwise runs fn(response) |
.promise([$]) | Returns a promise; with $, an error ends that operation |
.debug() | Prints the input and the result to the console |
With several operations the response is an object with the result of each one.
CALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {
console.log(err, response);
});
var users = await CALL('-Users --> list').query({ page: 1 }).promise();
method
EXEC(name, [model], [callback], [controller])
Runs schema operations from code. $ACTION() is an alias.
EXEC(name, [model], [callback], [controller])| Parameter | Type | Description |
|---|---|---|
name |
String |
Schema --> operations with a method prefix. |
model? |
Object |
Data for the operation. |
callback? |
Function |
function(err, response). |
controller? |
Controller|Object |
The request, or an object with query, params, user, id… |
Returns Promise A promise when there is no callback.
name is +Schema --> operations (or -, #, or a method like POST Schema --> insert). Instead of a controller you can pass an object with query, params, user, session, body, headers and id. Without a callback it returns a promise. For actions declared with NEWACTION(), use CALL().
EXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {
console.log(err, response);
});
var list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });
method
MAKE(schema, model, [callback], [novalidate], [controller])
since 0.0.63
Converts and validates a model with a schema, without running any operation.
MAKE(schema, model, [callback], [novalidate], [controller])| Parameter | Type | Description |
|---|---|---|
schema |
String |
Name of the schema. |
model |
Object |
Data to validate. |
callback? |
Function |
function(err, model). |
novalidate? |
Boolean |
true only converts the data. Default: false |
controller? |
Controller |
A controller that gets the error instead of the promise. |
Returns Promise The validated model, when there is no callback.
Without a callback it returns a promise.
// Users: name is required
MAKE('Users', { name: '' }, function(err, model) {
console.log(err); // an ErrorBuilder with the invalid name
});
var model = await MAKE('Users', { name: 'Peter' });
method
$OPERATION(schema, name, [options], [callback], [controller])
Runs an operation of a schema, added with schema.addOperation(), from code.
$OPERATION(schema, name, [options], [callback], [controller])| Parameter | Type | Description |
|---|---|---|
schema |
String |
The name of the schema. |
name |
String |
The name given in schema.addOperation(). |
options? |
Object |
Custom options, available as $.options. |
callback? |
Function |
function(err, response). |
controller? |
Controller|Object |
The controller, or a $ object. |
Returns Boolean true when the schema exists.
schema.addOperation(name, operation, [filter]) links a name in the schema to a global operation declared with NEWOPERATION(). $OPERATION() runs it: the schema calls OPERATION(operation, $.model, $.callback, schemaName, $), so the operation answers through the schema and shares its controller.
The model is not prepared or validated: $.model is an empty object, and the options arrive as $.options. Schema middleware still runs. When options is a function, it is the callback. A missing schema calls the callback with the error Schema "name" not found.; a schema without the operation answers with Schema "name" doesn't contain "Operation.name" operation.
Do not confuse it with OPERATION(), which runs a global operation directly.
NEWOPERATION('newsletter', function($) {
// $.controller is the controller passed to $OPERATION()
$.success();
});
NEWSCHEMA('Users', function(schema) {
schema.addOperation('subscribe', 'newsletter');
});
$OPERATION('Users', 'subscribe', function(err, response) {
console.log(err, response);
});
method
$TASK(schema, name, [options], [callback], [controller])
Runs a task of a schema, added with schema.addTask(), from code.
$TASK(schema, name, [options], [callback], [controller])| Parameter | Type | Description |
|---|---|---|
schema |
String |
The name of the schema. |
name |
String |
The name given in schema.addTask(). |
options? |
Object |
Custom options, available as $.options. |
callback? |
Function |
function(err, response). |
controller? |
Controller|Object |
The controller, or a $ object. |
Returns Boolean true when the schema exists.
schema.addTask(name, task, [filter], [callback]) links a name in the schema to a task step declared with NEWTASK() (task is 'name/step'). $TASK() runs it: the schema starts TASK(task, $.callback, $) with $.model as the value of the task. With the callback of addTask(), the schema calls callback($, err, response) instead and you answer yourself.
The model is not prepared or validated: $.model is an empty object, and the options arrive as $.options. When options is a function, it is the callback. A missing schema calls the callback with the error Schema "name" not found.
NEWTASK('Import', function(push) {
push('run', function($, value) {
$.success();
});
});
NEWSCHEMA('Products', function(schema) {
schema.addTask('import', 'Import/run');
});
$TASK('Products', 'import', function(err, response) {
console.log(err, response);
});
method
FAKE(schema, [onlyrequired])
Returns an object with random data that matches a schema, for tests and demos.
FAKE(schema, [onlyrequired])| Parameter | Type | Description |
|---|---|---|
schema |
String|Object |
A schema name, an inline declaration or an object of types. |
onlyrequired? |
Boolean |
Fills only the required fields. Default: false |
Returns Object The fake model.
schema is the name of a schema, an inline declaration like 'name:String, email:Email' or an object like { id: UID, name: 'String(30)' }. Each field gets a random value of its type: emails, phones, ZIP codes, URLs, identifiers (UID, GUID), numbers, dates, booleans and strings (cut by the declared length, at most 30 characters). Arrays get two items, enums and key-value lists one of their values, and fields of another schema a nested fake object.
Some field names give realistic values: firstname, lastname, fullname, company, country, currency, language, age, birthdate.
With onlyrequired, only required fields of a named schema are filled.
var model = FAKE('Users');
$INSERT('Users', model, function(err, response) {
console.log(err, response);
});
var user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });
var item = FAKE('name:String, price:Number, tags:[String]');
method
schema.setQueryExtension(fn)
Adds an extension to the query operation.
schema.setQueryExtension(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, data, next). $ is the options of the running operation, data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing the query operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same the query operation. Alias: schema.setListExtension().
// schemas/users.js
NEWSCHEMA('Users', function(schema) {
schema.define('name', String, true);
schema.setQuery(function($, model) {
$.extend(model, function() {
$.success();
});
});
});
// plugins/audit/index.js
GETSCHEMA('Users', function(err, schema) {
schema.setQueryExtension(function($, data, next) {
// data === the model passed to $.extend()
next();
});
});
method
schema.setReadExtension(fn)
Adds an extension to the read operation.
schema.setReadExtension(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, data, next). $ is the options of the running operation, data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing the read operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same the read operation. Alias: schema.setGetExtension().
// schemas/users.js
NEWSCHEMA('Users', function(schema) {
schema.define('name', String, true);
schema.setRead(function($, model) {
$.extend(model, function() {
$.success();
});
});
});
// plugins/audit/index.js
GETSCHEMA('Users', function(err, schema) {
schema.setReadExtension(function($, data, next) {
// data === the model passed to $.extend()
next();
});
});
method
schema.setInsertExtension(fn)
Adds an extension to the insert operation.
schema.setInsertExtension(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, data, next). $ is the options of the running operation, data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing the insert operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same the insert operation.
// schemas/users.js
NEWSCHEMA('Users', function(schema) {
schema.define('name', String, true);
schema.setInsert(function($, model) {
$.extend(model, function() {
$.success();
});
});
});
// plugins/audit/index.js
GETSCHEMA('Users', function(err, schema) {
schema.setInsertExtension(function($, data, next) {
// data === the model passed to $.extend()
next();
});
});
method
schema.setUpdateExtension(fn)
Adds an extension to the update operation.
schema.setUpdateExtension(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, data, next). $ is the options of the running operation, data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing the update operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same the update operation.
// schemas/users.js
NEWSCHEMA('Users', function(schema) {
schema.define('name', String, true);
schema.setUpdate(function($, model) {
$.extend(model, function() {
$.success();
});
});
});
// plugins/audit/index.js
GETSCHEMA('Users', function(err, schema) {
schema.setUpdateExtension(function($, data, next) {
// data === the model passed to $.extend()
next();
});
});
method
schema.setPatchExtension(fn)
Adds an extension to the patch operation.
schema.setPatchExtension(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, data, next). $ is the options of the running operation, data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing the patch operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same the patch operation.
// schemas/users.js
NEWSCHEMA('Users', function(schema) {
schema.define('name', String, true);
schema.setPatch(function($, model) {
$.extend(model, function() {
$.success();
});
});
});
// plugins/audit/index.js
GETSCHEMA('Users', function(err, schema) {
schema.setPatchExtension(function($, data, next) {
// data === the model passed to $.extend()
next();
});
});
method
schema.setRemoveExtension(fn)
Adds an extension to the remove operation.
schema.setRemoveExtension(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, data, next). $ is the options of the running operation, data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing the remove operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same the remove operation.
// schemas/users.js
NEWSCHEMA('Users', function(schema) {
schema.define('name', String, true);
schema.setRemove(function($, model) {
$.extend(model, function() {
$.success();
});
});
});
// plugins/audit/index.js
GETSCHEMA('Users', function(err, schema) {
schema.setRemoveExtension(function($, data, next) {
// data === the model passed to $.extend()
next();
});
});
method
schema.setSaveExtension(fn)
Adds an extension to the save operation.
schema.setSaveExtension(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function($, data, next). $ is the options of the running operation, data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing the save operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same the save operation.
// schemas/users.js
NEWSCHEMA('Users', function(schema) {
schema.define('name', String, true);
schema.setSave(function($, model) {
$.extend(model, function() {
$.success();
});
});
});
// plugins/audit/index.js
GETSCHEMA('Users', function(err, schema) {
schema.setSaveExtension(function($, data, next) {
// data === the model passed to $.extend()
next();
});
});
method
schema.addWorkflowExtension(name, fn)
Adds an extension to a workflow.
schema.addWorkflowExtension(name, fn)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the workflow. |
fn |
Function |
function($, data, next). data is the value passed to $.extend(). |
Returns SchemaBuilderEntity The schema, for chaining.
An extension is a function function($, data, next) that you add to an existing workflow, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls $.extend(data, [callback]), in the order they were added. With a callback, each extension must call next(); without one, next does nothing. Several extensions can be added to the same workflow. Alias: schema.addExtension().
NEWSCHEMA('Orders', function(schema) {
schema.addWorkflow('send', function($) {
$.extend($.model);
$.success();
});
schema.addWorkflowExtension('send', function($, data) {
// runs synchronously, next() is not needed
console.log('Order sent', data.id);
});
});
method
$.extend([data], [callback])
Runs the extensions of the current operation.
$.extend([data], [callback])| Parameter | Type | Description |
|---|---|---|
data? |
Object |
A value passed to every extension as its second argument. |
callback? |
Function |
Runs after the last extension. |
Returns Boolean true when extensions exist, otherwise undefined.
It runs the extensions added with schema.setSaveExtension(), schema.addWorkflowExtension() and the others for the running operation. Without callback, all extensions run at once. With callback, they run one by one (each calls next()) and callback runs at the end, also when there are no extensions. The method returns true when the operation has extensions.
schema.setInsert(function($, model) {
model.id = UID();
$.extend(model, function() {
NOSQL('users').insert(model);
$.success(model.id);
});
});
method
schema.csrf([enable])
since 0.0.37
Requires a valid CSRF token for every route of the schema.
schema.csrf([enable])| Parameter | Type | Description |
|---|---|---|
enable? |
Boolean |
false turns it off. Default: true |
Returns SchemaBuilderEntity The schema, for chaining.
The routes of the schema then work like routes with the csrf flag: the token from controller.csrf() must arrive in the x-csrf-token header or the ?csrf= argument. An invalid token answers the error Invalid CSRF token.
NEWSCHEMA('Contact', function(schema) {
schema.csrf();
schema.define('email', 'Email', true);
schema.setInsert(function($, model) {
$.success();
});
});
method
schema.encrypt([enable])
Encrypts the responses of the routes of the schema.
schema.encrypt([enable])| Parameter | Type | Description |
|---|---|---|
enable? |
Boolean |
false turns it off. Default: true |
Returns SchemaBuilderEntity The schema, for chaining.
Text responses are encrypted with CONF.secret_encryption and get the header X-Encryption: a. Without secret_encryption in the configuration nothing is encrypted.
// config: secret_encryption : my-secret-key
NEWSCHEMA('Wallet', function(schema) {
schema.encrypt();
schema.setRead(function($) {
$.callback({ balance: 100 });
});
});
method
schema.compress([enable])
Leaves out null and undefined values from the JSON responses of the schema.
schema.compress([enable])| Parameter | Type | Description |
|---|---|---|
enable? |
Boolean |
false turns it off. Default: true |
Returns SchemaBuilderEntity The schema, for chaining.
The JSON answer of the routes of the schema is serialized without the keys whose value is null or undefined, so it is smaller.
NEWSCHEMA('Products', function(schema) {
schema.compress();
schema.setQuery(function($) {
// { id: 1, note: null } is answered as { "id": 1 }
$.callback([{ id: 1, note: null }]);
});
});
method
schema.allow(field, [field2], [...])
Copies fields that the schema does not define.
schema.allow(field, [field2], [...])| Parameter | Type | Description |
|---|---|---|
field |
String|Array |
A name, a list separated by commas or an array of names. |
Returns SchemaBuilderEntity The schema, for chaining.
The listed fields are copied from the input into the model as they are: without conversion and without validation. One string with names separated by commas works too.
NEWSCHEMA('Events', function(schema) {
schema.define('name', String, true);
schema.allow('meta, tags');
});
method
schema.verify(name, fn, [cache])
Adds an asynchronous check of one field.
schema.verify(name, fn, [cache])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the field. |
fn |
Function |
function($). |
cache? |
String |
How long the result is kept, for example '10 minutes'. |
Returns SchemaBuilderEntity The schema, for chaining.
The check runs after the validation, only when the field has a value. fn($) gets $.value, $.model, $.name, $.user, $.query and the other request values. Call $.next([value]) (or $.success([value])) to accept the value, optionally with a new one, or $.invalid(error) to reject it; a rejected field is set to null. With cache (an expiration such as '5 minutes') the result for the same value is kept in the cache.
NEWSCHEMA('Companies', function(schema) {
schema.define('country', 'Upper(2)', true);
schema.verify('country', function($) {
NOSQL('countries').one().where('id', $.value).callback(function(err, item) {
if (item)
$.next();
else
$.invalid('error-country');
});
}, '10 minutes');
});
method
schema.clear()
Removes all fields of the schema.
schema.clear()Returns SchemaBuilderEntity The schema, for chaining.
It removes the defined fields, the required fields, the checks of schema.verify() and the fields of schema.allow(). The operations stay.
GETSCHEMA('Products', function(err, schema) {
schema.clear();
schema.define('name', String, true);
});
method
schema.setPrimary(name)
Names the primary key of the schema.
schema.setPrimary(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the field. |
Returns SchemaBuilderEntity The schema, for chaining.
The name is stored in schema.primary, and schema.inherit() copies it. The framework does not use it in the operations: it is information for your own code.
NEWSCHEMA('Users', function(schema) {
schema.define('id', 'UID');
schema.setPrimary('id');
});
method
schema.setError(fn)
Sets a function that runs when an operation or the validation of the schema ends with errors.
schema.setError(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(error, model, type, [name]). |
Returns SchemaBuilderEntity The schema, for chaining.
fn(error, model, type, [name]) gets the ErrorBuilder, the model, the type of the operation ('make' for the validation, 'save', 'workflow', ...) and the name of a workflow. You can read or change the errors before they are answered.
NEWSCHEMA('Orders', function(schema) {
schema.setError(function(error, model, type) {
console.log('Orders', type, error.items);
});
});
method
schema.addTask(name, task, [filter], [callback])
Adds an operation of the schema that runs a task.
schema.addTask(name, task, [filter], [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the operation. |
task |
String |
The task in the form 'name/start'. |
filter? |
String |
Fields of the query string. |
callback? |
Function |
function($, err, response). |
Returns SchemaBuilderEntity The schema, for chaining.
Calling the operation (for example CALL('Schema --> name') or *Schema --> name in a route) runs TASK(task) with the model as its value. The answer of the task is the answer of the operation. With callback($, err, response) you answer yourself.
NEWTASK('Import', function(push) {
push('start', function($, value) {
$.end(value.url);
});
});
NEWSCHEMA('Feeds', function(schema) {
schema.define('url', 'URL', true);
schema.addTask('import', 'Import/start');
});
// ROUTE('POST /api/feeds/import/ *Feeds --> import');
method
schema.addOperation(name, operation, [filter])
Adds an operation of the schema that runs an operation of NEWOPERATION().
schema.addOperation(name, operation, [filter])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the operation in the schema. |
operation |
String |
The name of the operation from NEWOPERATION(). |
filter? |
String |
Fields of the query string. |
Returns SchemaBuilderEntity The schema, for chaining.
Calling the schema operation (for example *Schema --> name in a route) runs OPERATION(operation) with the model as its value, and its answer is the answer of the schema operation.
NEWOPERATION('sendmail', function($) {
MAIL($.value.email, 'Hello', 'mails/hello', $.value, $.done());
});
NEWSCHEMA('Newsletter', function(schema) {
schema.define('email', 'Email', true);
schema.addOperation('send', 'sendmail');
});
// ROUTE('POST /api/newsletter/ *Newsletter --> send');
method
schema.cl(name, [value])
Reads or replaces the list of values of an enum field.
schema.cl(name, [value])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the field. |
value? |
Array|Object |
A new list of values. |
Returns Array|Object The current list, or undefined for other fields.
It works for fields defined with an array (enum) or an object (key-value). With value the list is replaced.
NEWSCHEMA('Tickets', function(schema) {
schema.define('status', ['open', 'closed']);
});
ON('ready', function() {
GETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);
});
method
schema.props()
Describes the fields of the schema.
schema.props()Returns Object The description of the fields.
It returns an object with one key per field and its type (number, string, uid, email, boolean, date, ...), and required and length when they are set. Useful to describe the schema to a client.
function fields() {
this.json(GETSCHEMA('Users').props());
}
method
schema.make(model, [callback])
Prepares and validates a model from code.
schema.make(model, [callback])| Parameter | Type | Description |
|---|---|---|
model |
Object |
The input. |
callback? |
Function |
function(err, model). |
Returns Object The prepared model (before the asynchronous checks).
It converts the input by the fields of the schema, validates it and runs the checks of schema.verify(). callback(err, model) gets the ErrorBuilder or the prepared model. Alias: schema.load().
GETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {
if (err)
console.log(err.items);
else
console.log(model);
});
method
schema.validate(model)
Validates a model without converting it.
schema.validate(model)| Parameter | Type | Description |
|---|---|---|
model |
Object |
The model. |
Returns ErrorBuilder The errors; .is is true when there are some.
It checks the required fields and the validation of every field. It does not run the checks of schema.verify().
var errors = GETSCHEMA('Users').validate({ name: '' });
if (errors.is)
console.log(errors.items);
method
schema.default()
Creates a model with the default values of the fields.
schema.default()Returns Object A new model.
Each field gets its default: 0 for numbers, '' for strings, false for booleans, NOW for dates, [] for arrays and a default model for a field of another schema. Alias: schema.create().
function create() {
this.view('form', GETSCHEMA('Products').default());
}
method
schema.destroy()
Removes the schema.
schema.destroy()Returns undefined Nothing.
The schema is removed from the list of schemas and its function of schema.setDestroy() runs.
GETSCHEMA('Temporary').destroy();
method
schema.workflow(name, model, [options], callback, [controller])
Runs a workflow of the schema from code with a model.
schema.workflow(name, model, [options], callback, [controller])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the workflow. |
model |
Object |
The input. |
options? |
Object |
A value available as $.options. |
callback |
Function |
function(err, response). |
controller? |
Controller |
A controller or $ to take the user and the request from. |
Returns SchemaBuilderEntity The schema, for chaining.
The model is prepared and validated first, like in a route. schema.workflow2(name, [options], callback, [controller]) runs it without a model and without validation. For most code CALL() and EXEC() are simpler.
GETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {
console.log(err, response);
});
method
schema.query([options], callback, [controller])
Runs the query operation from code.
schema.query([options], callback, [controller])| Parameter | Type | Description |
|---|---|---|
options? |
Object |
A value available as $.options. |
callback |
Function |
function(err, response). |
controller? |
Controller |
A controller or $. |
Returns SchemaBuilderEntity The schema, for chaining.
schema.read() (alias schema.get()) and schema.remove() work the same way for the read and remove operations. These run without a model.
GETSCHEMA('Products').query(function(err, items) {
console.log(items);
});