---
title: Schemas
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/schemas/
updated: 2026-11-16T15:41:15.818Z
---

# Schemas

> NEWSCHEMA(), schema methods, the $ object of operations, NEWACTION() and how to run operations from code.

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](../../guides/schemas/) explains how the parts work together; this page is the exact reference.

## API

### NEWSCHEMA(name, [declaration])

Type: `method`

Declares a schema: its fields, validation and operations.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the schema, used in routes (`*Users`) and in `CALL()`. |
| `declaration` | `Function` | no |  | `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).

Example: A schema with fields and an operation
```js
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);
	});

});
```

Example: Remove a schema
```js
NEWSCHEMA('Users', null);
```

### GETSCHEMA(name, [callback], [timeout])

Type: `method`

Returns a declared schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the schema. |
| `callback` | `Function` | no |  | `function(err, schema)`, called when the schema exists. |
| `timeout` | `Number` | no | `20000` | How long to wait, in milliseconds. |

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)`.

Example: Read a schema
```js
var schema = GETSCHEMA('Users');
console.log(schema.fields);
```

### schema.define(name, type, [required], [error], [xss])

Type: `method`

Declares a field: its type, whether it is required and its error message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Array` | yes |  | Name of the field, or an array of names. |
| `type` | `Function|String|Array|Object` | yes |  | Type of the field (see above), or `null` to remove it. |
| `required` | `Boolean|Function|String` | no | `false` | `true`; a function `(value, model)` that returns `true`, `false` or an error message; or an error message, which also makes the field required. |
| `error` | `String` | no |  | Error message when the field is invalid. `@key` reads a resource. |
| `xss` | `Boolean|Number` | no |  | 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.

Example: Fields
```js
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');
```

Example: Default values
```js
schema.define('count', Number)(10);
schema.define('created', Date)(() => new Date());
```

### schema.required(name, [fn])

Type: `method`

Makes a declared field required, always or only when a condition holds.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the field, or several names separated by commas. |
| `fn` | `Function|Boolean` | no |  | `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.

Example: Required only on insert
```js
schema.define('password', 'String(30)');
schema.required('password', (model, operations) => !!operations.insert);
```

### schema.undefine(name)

Type: `method` · Since: `0.0.46`

Removes a declared field.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the field. |

Returns: `SchemaBuilderEntity` The schema, for chaining.

Example: Remove a field of an inherited schema
```js
schema.inherit('Users');
schema.undefine('password');
```

### schema.inherit(name)

Type: `method`

Copies fields, operations and settings of another schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Inherit
```js
NEWSCHEMA('Admins', function(schema) {
	schema.inherit('Users');
	schema.define('level', Number);
});
```

### schema.array()

Type: `method` · Since: `0.0.63`

The schema receives an array of items instead of one object.

Returns: `SchemaBuilderEntity` The schema, for chaining.

Every item is converted and validated. Data that is not an array becomes an empty array.

Example: An array of items
```js
NEWSCHEMA('Products', function(schema) {
	schema.array();
	schema.define('id', 'UID', true);
	schema.define('count', Number, true);
});
```

### schema.action(name, options)

Type: `method` · Since: `0.0.67`

Declares an operation with its input, query, parameters and permissions in one object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the operation, optionally with URL parameters (`read/{id:UID}`). It can be left out when `options` has `id` or `name`. |
| `options` | `Object` | yes |  | 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`.

Example: Actions with input, query and permissions
```js
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);
		}
	});

});
```

Example: Routes
```js
ROUTE('GET  /api/users/ *Users --> list');
ROUTE('POST /api/users/ *Users --> create');
```

Example: Cache the response for 10 minutes
```js
schema.action('stats', {
	query: 'year:Number',
	cache: { query: true, expire: '10 minutes' },
	action: function($) {
		// ...
	}
});
```

### schema.setSave(fn, [filter])

Type: `method`

Sets the save operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |
| `filter` | `String` | no |  | 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')`.

Example: Declare and route it
```js
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');
```

### schema.setInsert(fn, [filter])

Type: `method`

Sets the insert operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |
| `filter` | `String` | no |  | 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')`.

Example: Declare and route it
```js
schema.setInsert(function($, model) {
	model.id = UID();
	NOSQL('users').insert(model);
	$.success(model.id);
});

// ROUTE('POST /api/users/ *Users --> insert');
```

### schema.setUpdate(fn, [filter])

Type: `method`

Sets the update operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |
| `filter` | `String` | no |  | 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')`.

Example: Declare and route it
```js
schema.setUpdate(function($, model) {
	NOSQL('users').modify(model).where('id', $.id);
	$.success();
});

// ROUTE('PUT /api/users/{id}/ *Users --> update');
```

### schema.setPatch(fn, [filter])

Type: `method`

Sets the patch operation, which changes only the fields that were sent.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |
| `filter` | `String` | no |  | 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')`.

Example: Declare and route it
```js
schema.setPatch(function($, model) {
	NOSQL('users').modify(model).where('id', $.id);
	$.success();
});

// ROUTE('PATCH /api/users/{id}/ *Users --> patch');
```

### schema.setRead(fn, [filter])

Type: `method`

Sets the read operation. `schema.setGet()` is an alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |
| `filter` | `String` | no |  | 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`.

Example: Declare and route it
```js
schema.setRead(function($) {
	NOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');
});

// ROUTE('GET /api/users/{id}/ *Users --> read');
```

### schema.setQuery(fn, [filter])

Type: `method`

Sets the query operation, which lists items. `schema.setList()` is an alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |
| `filter` | `String` | no |  | 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`.

Example: A list with a filter
```js
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');
```

### schema.setRemove(fn, [filter])

Type: `method`

Sets the remove operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |
| `filter` | `String` | no |  | 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')`.

Example: Declare and route it
```js
schema.setRemove(function($) {
	NOSQL('users').remove().where('id', $.id);
	$.success();
});

// ROUTE('DELETE /api/users/{id}/ *Users --> remove');
```

### schema.addWorkflow(name, fn, [filter])

Type: `method`

Adds an operation with your own name. `schema.add()` is an alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the operation. |
| `fn` | `Function|String` | yes |  | `function($, model)`, or `'Schema --> name'`. |
| `filter` | `String` | no |  | 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.

Example: A custom operation
```js
schema.addWorkflow('activate', function($) {
	NOSQL('users').modify({ active: true }).where('id', $.id);
	$.success();
});

// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');
```

Example: Reuse an operation of another schema
```js
schema.addWorkflow('check', 'Common --> check');
```

### schema.middleware(fn)

Type: `method`

Adds a function that runs before every operation of the schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Only for signed-in users
```js
schema.middleware(function($, next) {
	if ($.user)
		next();
	else {
		$.invalid(401);
		next(true);
	}
});
```

### schema.setResource(name)

Type: `method`

Sets the resource file with the error messages of the schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Messages from a resource
```js
schema.setResource('errors');
schema.setPrefix('user_');
schema.define('email', 'Email', true); // key: user_email
```

### schema.setTimer(fn)

Type: `method` · Since: `0.0.63`

Sets a function that runs every minute. `schema.setService()` is an alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(counter)`; `counter` counts the minutes. |

Returns: `SchemaBuilderEntity` The schema, for chaining.

Example: Clean every hour
```js
schema.setTimer(function(counter) {
	if (counter % 60 === 0)
		NOSQL('sessions').remove().where('expire', '<', NOW);
});
```

### schema.setDestroy(fn)

Type: `method` · Since: `0.0.63`

Sets a function that runs when the schema is removed or replaced.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function()`. |

Returns: `SchemaBuilderEntity` The schema, for chaining.

Example: Free resources
```js
schema.setDestroy(function() {
	clearInterval(timer);
});
```

### $.callback([value])

Type: `method`

Ends the operation and answers with a value or an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|Error` | no |  | 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.

Example: Answer with data
```js
schema.setQuery(function($) {
	NOSQL('users').find().callback($.callback);
});
```

### $.success([success], [value])

Type: `method`

Ends the operation and answers `{ "success": true, "value": ... }`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `success` | `Boolean` | no | `true` | The result. |
| `value` | `Object` | no |  | A value sent as `value`. |

Returns: `SchemaOptions` `$`.

With one argument that is not a boolean, it is the value. `$.success(false)` answers `{ "success": false }`.

Example: Answer with the new id
```js
$.success(model.id);
// { "success": true, "value": "1fd0b001ez51d" }
```

### $.invalid(name, [message])

Type: `method`

Ends the operation with an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Number|Error` | yes |  | Name of the field, a message, a status code or an error. |
| `message` | `String` | no |  | 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.

Example: Errors
```js
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);
	});
});
```

### $.done([value])

Type: `method`

Returns a callback `(err, response)` that ends the operation with success or with the error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean|Object` | no |  | `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`.

Example: Answer after a database call
```js
schema.setRemove(function($) {
	NOSQL('users').remove().where('id', $.id).callback($.done());
});
```

### $.successful(fn)

Type: `method`

Returns a callback that ends the operation on an error and otherwise runs `fn`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(response)`, run with `$` as `this`. |

Returns: `Function` `function(err, response)`.

Example: Continue only without an error
```js
NOSQL('users').one().where('id', $.id).callback($.successful(function(user) {
	$.callback(user || {});
}));
```

### $.promisify(fn, [a], [b], [c])

Type: `method` · Since: `0.0.97`

Runs a function with a Node.js style callback and returns a promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | A function whose last argument is `callback(err, response)`. |
| `a, b, c` | `Object` | no |  | 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.

Example: Await a callback function
```js
schema.action('read', {
	action: async function($) {
		var data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));
		$.callback(data.toString('utf8').parseJSON());
	}
});
```

### $.redirect(url)

Type: `method`

Ends the operation and redirects the request to another URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The target URL. |

Returns: `SchemaOptions` `$`.

Example: Redirect
```js
$.redirect('/login/');
```

### $.action(name, [model])

Type: `method`

Runs another action or operation from inside an operation, with the same controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Operation of this schema, `Schema --> operation` or an action name. |
| `model` | `Object` | no |  | 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()`.

Example: Call another operation
```js
schema.action('create', {
	input: '*name:String',
	action: async function($, model) {
		var user = await $.action('-read').promise($);
		// ...
	}
});
```

### $.on(name, fn)

Type: `method` · Since: `0.0.63`

Listens to an event of the operation: `error`, `response` or `end`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | `error`, `response` or `end`. |
| `fn` | `Function` | yes |  | 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.

Example: Log the end of an operation
```js
$.on('end', function(err, response) {
	console.log('done', err, response);
});
```

### $.model

Type: `property`

The validated model of the operation.

Returns: `Object`

It contains only the declared fields, converted to their types. Operations also get it as the second argument. `$.value` is an alias.

Example: Read the model
```js
schema.setInsert(function($) {
	console.log($.model.name);
	$.success();
});
```

### $.query

Type: `property`

The query string of the request.

Returns: `Object`

In an action with the `query` option, the fields are converted and validated.

Example: Read the query
```js
// GET /api/users/?page=2
var page = $.query.page;
```

### $.params

Type: `property`

The dynamic parameters of the route URL.

Returns: `Object`

In an action with the `params` option, they are converted and validated.

Example: Read a parameter
```js
// ROUTE('GET /api/users/{id}/ *Users --> read');
var id = $.params.id;
```

### $.id

Type: `property`

The first dynamic parameter of the route URL, usually the id.

Returns: `String`

Example: Read by id
```js
// ROUTE('GET /api/users/{id}/ *Users --> read');
NOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');
```

### $.user

Type: `property`

The signed-in user of the request, or `null`.

Returns: `Object`

Actions with `user`, `sa` or `permissions` check it before they run. `$.session` holds the session.

Example: Save the author
```js
model.userid = $.user.id;
```

### $.keys

Type: `property`

In a `PATCH` request, the names of the fields that were sent; otherwise `null`.

Returns: `Array`

Only these fields are converted and validated.

Example: Patch only the sent fields
```js
schema.setPatch(function($, model) {
	console.log($.keys); // ['name']
	NOSQL('users').modify(model).where('id', $.id);
	$.success();
});
```

### $.filter

Type: `property`

The query string converted with the `filter` of the operation.

Returns: `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.

Example: Typed query
```js
schema.setQuery(function($) {
	console.log($.filter.page); // a number
	$.callback([]);
}, 'page:Number, limit:Number');
```

### $.controller

Type: `property`

The controller of the request, or nothing when the operation runs from code.

Returns: `Controller`

`$` also reads some properties of the controller directly: `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` and `$.sessionid`.

Example: Read the request
```js
console.log($.ip, $.language, $.headers['user-agent']);
```

### $.responses

Type: `property`

The responses of the previous operations when a route or `CALL()` runs several of them.

Returns: `Object`

`$.response(name)` returns one of them.

Example: Use the result of a previous operation
```js
// ROUTE('POST /api/orders/ *Orders --> check insert');
schema.setInsert(function($, model) {
	var check = $.response('check');
	// ...
});
```

### NEWACTION(name, options)

Type: `method` · Since: `0.0.81`

Declares an action that does not belong to a schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the action, for example `Users/create`. It can be left out when `options` has `id` or `name`. |
| `options` | `Object` | yes |  | 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.

Example: An action and its route
```js
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');
```

Example: An action with its own API route
```js
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" }
```

### CALL(name, [model], [controller])

Type: `method` · Since: `0.0.67`

Runs actions or schema operations from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Action name or `Schema --> operations`, optionally with a `+`, `-` or `#` prefix. |
| `model` | `Object` | no |  | Data for the operation. It is validated. |
| `controller` | `Controller|SchemaOptions` | no |  | 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.

Example: Run an action
```js
CALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {
	console.log(err, response);
});
```

Example: Await a schema operation
```js
var users = await CALL('-Users --> list').query({ page: 1 }).promise();
```

### EXEC(name, [model], [callback], [controller])

Type: `method`

Runs schema operations from code. `$ACTION()` is an alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | `Schema --> operations` with a method prefix. |
| `model` | `Object` | no |  | Data for the operation. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `controller` | `Controller|Object` | no |  | 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()`.

Example: Insert from code
```js
EXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {
	console.log(err, response);
});
```

Example: With a query and a user
```js
var list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });
```

### MAKE(schema, model, [callback], [novalidate], [controller])

Type: `method` · Since: `0.0.63`

Converts and validates a model with a schema, without running any operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Name of the schema. |
| `model` | `Object` | yes |  | Data to validate. |
| `callback` | `Function` | no |  | `function(err, model)`. |
| `novalidate` | `Boolean` | no | `false` | `true` only converts the data. |
| `controller` | `Controller` | no |  | 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.

Example: Validate data
```js
// 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' });
```

### $OPERATION(schema, name, [options], [callback], [controller])

Type: `method`

Runs an operation of a schema, added with `schema.addOperation()`, from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | The name of the schema. |
| `name` | `String` | yes |  | The name given in `schema.addOperation()`. |
| `options` | `Object` | no |  | Custom options, available as `$.options`. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `controller` | `Controller|Object` | no |  | 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.

Example: Link and run an operation
```js
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);
});
```

### $TASK(schema, name, [options], [callback], [controller])

Type: `method`

Runs a task of a schema, added with `schema.addTask()`, from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | The name of the schema. |
| `name` | `String` | yes |  | The name given in `schema.addTask()`. |
| `options` | `Object` | no |  | Custom options, available as `$.options`. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `controller` | `Controller|Object` | no |  | 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.`

Example: Link and run a task
```js
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);
});
```

### FAKE(schema, [onlyrequired])

Type: `method`

Returns an object with random data that matches a schema, for tests and demos.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String|Object` | yes |  | A schema name, an inline declaration or an object of types. |
| `onlyrequired` | `Boolean` | no | `false` | Fills only the required fields. |

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.

Example: From a schema
```js
var model = FAKE('Users');

$INSERT('Users', model, function(err, response) {
	console.log(err, response);
});
```

Example: Inline
```js
var user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });
var item = FAKE('name:String, price:Number, tags:[String]');
```

### schema.setQueryExtension(fn)

Type: `method`

Adds an extension to the `query` operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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()`.

Example: Extend an operation from a plugin
```js
// 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();
	});
});
```

### schema.setReadExtension(fn)

Type: `method`

Adds an extension to the `read` operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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()`.

Example: Extend an operation from a plugin
```js
// 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();
	});
});
```

### schema.setInsertExtension(fn)

Type: `method`

Adds an extension to the `insert` operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Extend an operation from a plugin
```js
// 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();
	});
});
```

### schema.setUpdateExtension(fn)

Type: `method`

Adds an extension to the `update` operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Extend an operation from a plugin
```js
// 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();
	});
});
```

### schema.setPatchExtension(fn)

Type: `method`

Adds an extension to the `patch` operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Extend an operation from a plugin
```js
// 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();
	});
});
```

### schema.setRemoveExtension(fn)

Type: `method`

Adds an extension to the `remove` operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Extend an operation from a plugin
```js
// 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();
	});
});
```

### schema.setSaveExtension(fn)

Type: `method`

Adds an extension to the `save` operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Extend an operation from a plugin
```js
// 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();
	});
});
```

### schema.addWorkflowExtension(name, fn)

Type: `method`

Adds an extension to a workflow.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the workflow. |
| `fn` | `Function` | yes |  | `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()`.

Example: Extend a workflow
```js
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);
	});
});
```

### $.extend([data], [callback])

Type: `method`

Runs the extensions of the current operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | A value passed to every extension as its second argument. |
| `callback` | `Function` | no |  | 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.

Example: Wait for the extensions
```js
schema.setInsert(function($, model) {
	model.id = UID();
	$.extend(model, function() {
		NOSQL('users').insert(model);
		$.success(model.id);
	});
});
```

### schema.csrf([enable])

Type: `method` · Since: `0.0.37`

Requires a valid CSRF token for every route of the schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` turns it off. |

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`.

Example: Protect a form
```js
NEWSCHEMA('Contact', function(schema) {
	schema.csrf();
	schema.define('email', 'Email', true);
	schema.setInsert(function($, model) {
		$.success();
	});
});
```

### schema.encrypt([enable])

Type: `method`

Encrypts the responses of the routes of the schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` turns it off. |

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.

Example: Encrypted answers
```js
// config: secret_encryption : my-secret-key
NEWSCHEMA('Wallet', function(schema) {
	schema.encrypt();
	schema.setRead(function($) {
		$.callback({ balance: 100 });
	});
});
```

### schema.compress([enable])

Type: `method`

Leaves out `null` and `undefined` values from the JSON responses of the schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` turns it off. |

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.

Example: Smaller JSON
```js
NEWSCHEMA('Products', function(schema) {
	schema.compress();
	schema.setQuery(function($) {
		// { id: 1, note: null } is answered as { "id": 1 }
		$.callback([{ id: 1, note: null }]);
	});
});
```

### schema.allow(field, [field2], [...])

Type: `method`

Copies fields that the schema does not define.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `field` | `String|Array` | yes |  | 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.

Example: Free-form metadata
```js
NEWSCHEMA('Events', function(schema) {
	schema.define('name', String, true);
	schema.allow('meta, tags');
});
```

### schema.verify(name, fn, [cache])

Type: `method`

Adds an asynchronous check of one field.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the field. |
| `fn` | `Function` | yes |  | `function($)`. |
| `cache` | `String` | no |  | 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.

Example: Check a country code
```js
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');
});
```

### schema.clear()

Type: `method`

Removes all fields of the schema.

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.

Example: Define the fields again
```js
GETSCHEMA('Products', function(err, schema) {
	schema.clear();
	schema.define('name', String, true);
});
```

### schema.setPrimary(name)

Type: `method`

Names the primary key of the schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: A primary key
```js
NEWSCHEMA('Users', function(schema) {
	schema.define('id', 'UID');
	schema.setPrimary('id');
});
```

### schema.setError(fn)

Type: `method`

Sets a function that runs when an operation or the validation of the schema ends with errors.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Log invalid input
```js
NEWSCHEMA('Orders', function(schema) {
	schema.setError(function(error, model, type) {
		console.log('Orders', type, error.items);
	});
});
```

### schema.addTask(name, task, [filter], [callback])

Type: `method`

Adds an operation of the schema that runs a task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the operation. |
| `task` | `String` | yes |  | The task in the form `'name/start'`. |
| `filter` | `String` | no |  | Fields of the query string. |
| `callback` | `Function` | no |  | `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.

Example: A schema operation that runs a task
```js
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');
```

### schema.addOperation(name, operation, [filter])

Type: `method`

Adds an operation of the schema that runs an operation of `NEWOPERATION()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the operation in the schema. |
| `operation` | `String` | yes |  | The name of the operation from `NEWOPERATION()`. |
| `filter` | `String` | no |  | 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.

Example: Reuse an operation
```js
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');
```

### schema.cl(name, [value])

Type: `method`

Reads or replaces the list of values of an enum field.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the field. |
| `value` | `Array|Object` | no |  | 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.

Example: Values loaded later
```js
NEWSCHEMA('Tickets', function(schema) {
	schema.define('status', ['open', 'closed']);
});

ON('ready', function() {
	GETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);
});
```

### schema.props()

Type: `method`

Describes the fields of the schema.

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.

Example: Send the fields to a client
```js
function fields() {
	this.json(GETSCHEMA('Users').props());
}
```

### schema.make(model, [callback])

Type: `method`

Prepares and validates a model from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `model` | `Object` | yes |  | The input. |
| `callback` | `Function` | no |  | `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()`.

Example: Validate a value
```js
GETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {
	if (err)
		console.log(err.items);
	else
		console.log(model);
});
```

### schema.validate(model)

Type: `method`

Validates a model without converting it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `model` | `Object` | yes |  | 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()`.

Example: Check a model
```js
var errors = GETSCHEMA('Users').validate({ name: '' });
if (errors.is)
	console.log(errors.items);
```

### schema.default()

Type: `method`

Creates a model with the default values of the fields.

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()`.

Example: An empty form
```js
function create() {
	this.view('form', GETSCHEMA('Products').default());
}
```

### schema.destroy()

Type: `method`

Removes the schema.

Returns: `undefined` Nothing.

The schema is removed from the list of schemas and its function of `schema.setDestroy()` runs.

Example: Remove a schema
```js
GETSCHEMA('Temporary').destroy();
```

### schema.workflow(name, model, [options], callback, [controller])

Type: `method`

Runs a workflow of the schema from code with a model.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the workflow. |
| `model` | `Object` | yes |  | The input. |
| `options` | `Object` | no |  | A value available as `$.options`. |
| `callback` | `Function` | yes |  | `function(err, response)`. |
| `controller` | `Controller` | no |  | 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.

Example: Run a workflow
```js
GETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {
	console.log(err, response);
});
```

### schema.query([options], callback, [controller])

Type: `method`

Runs the `query` operation from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no |  | A value available as `$.options`. |
| `callback` | `Function` | yes |  | `function(err, response)`. |
| `controller` | `Controller` | no |  | 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.

Example: List from code
```js
GETSCHEMA('Products').query(function(err, items) {
	console.log(items);
});
```
