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

# Schemi

> NEWSCHEMA(), i metodi dello schema, l'oggetto $ delle operazioni, NEWACTION() e come eseguire le operazioni dal codice.

Uno schema si dichiara con `NEWSCHEMA()`, di solito in un file della cartella `schemas/`; le azioni senza schema con `NEWACTION()`. Ogni operazione riceve l'oggetto `$`. La guida [Schemi e azioni](../../guides/schemas/) spiega come le parti lavorano insieme; questa pagina è il riferimento esatto.

## API

### NEWSCHEMA(name, [declaration])

Type: `method`

Dichiara uno schema: i suoi campi, la validazione e le operazioni.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dello schema, usato nelle route (`*Users`) e in `CALL()`. |
| `declaration` | `Function` | no |  | `function(schema)` che dichiara campi e operazioni, oppure `null` per rimuovere lo schema. |

Returns: `SchemaBuilderEntity` Il nuovo schema (niente quando viene rimosso).

La dichiarazione viene eseguita subito con lo schema come argomento e come `this`. Uno schema con lo stesso nome viene sostituito. Passa `null` come dichiarazione per rimuovere uno schema. Con una funzione come unico argomento, lo schema riceve un nome casuale (schema dinamico).

Example: Uno schema con campi e un'operazione
```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: Rimuovere uno schema
```js
NEWSCHEMA('Users', null);
```

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

Type: `method`

Restituisce uno schema dichiarato.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dello schema. |
| `callback` | `Function` | no |  | `function(err, schema)`, chiamata quando lo schema esiste. |
| `timeout` | `Number` | no | `20000` | Quanto attendere, in millisecondi. |

Returns: `SchemaBuilderEntity` Lo schema, oppure `undefined`. Niente quando viene passata una callback.

Con una callback, attende che lo schema sia dichiarato (20 secondi per impostazione predefinita) e chiama `callback(err, schema)`.

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

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

Type: `method`

Dichiara un campo: il suo tipo, se è obbligatorio e il suo messaggio di errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Array` | yes |  | Nome del campo, oppure un array di nomi. |
| `type` | `Function|String|Array|Object` | yes |  | Tipo del campo (vedi sopra), oppure `null` per rimuoverlo. |
| `required` | `Boolean|Function|String` | no | `false` | `true`; una funzione `(value, model)` che restituisce `true`, `false` o un messaggio di errore; oppure un messaggio di errore, che rende anche il campo obbligatorio. |
| `error` | `String` | no |  | Messaggio di errore quando il campo non è valido. `@key` legge una risorsa. |
| `xss` | `Boolean|Number` | no |  | Per le stringhe: `true` svuota un valore con XSS o SQL injection, `1` controlla solo XSS, `2` solo SQL injection. |

Returns: `Function` `function(value)` che imposta il valore predefinito (un valore o una funzione) e restituisce lo schema.

Tipi: `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`, un oggetto inline `'name:String, age:Number'`, un enum `['a', 'b']`, un oggetto chiave-valore, `Array` o `'[Type]'`, e il nome di un altro schema (`'Address'`, `'[Address]'`).

Un campo obbligatorio non deve essere vuoto: una stringa deve avere caratteri (e un valore valido per `Email`, `URL`, `UID` e simili), un numero deve essere maggiore di `0`, un booleano `true` e un array deve avere elementi. Un campo di un altro schema viene sempre validato.

La funzione che restituisce imposta il valore predefinito e restituisce lo schema. `type` `null` rimuove il campo. Un array di nomi dichiara più campi con lo stesso tipo.

Example: Campi
```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: Valori predefiniti
```js
schema.define('count', Number)(10);
schema.define('created', Date)(() => new Date());
```

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

Type: `method`

Rende obbligatorio un campo dichiarato, sempre o solo quando vale una condizione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del campo, oppure più nomi separati da virgole. |
| `fn` | `Function|Boolean` | no |  | `function(model, operations)` che restituisce `true` quando il campo deve essere validato; oppure `false` per rendere il campo facoltativo. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

`fn(model, operations)` decide a ogni validazione se il campo viene validato. `operations` è un oggetto con i nomi delle operazioni che la route esegue, quindi `operations.insert` è vero in inserimento. `false` al posto di una funzione rende di nuovo il campo facoltativo. Più nomi possono essere separati da virgole. Il campo deve essere dichiarato prima.

Example: Obbligatorio solo in inserimento
```js
schema.define('password', 'String(30)');
schema.required('password', (model, operations) => !!operations.insert);
```

### schema.undefine(name)

Type: `method` · Since: `0.0.46`

Rimuove un campo dichiarato.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del campo. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Example: Rimuovere un campo di uno schema ereditato
```js
schema.inherit('Users');
schema.undefine('password');
```

### schema.inherit(name)

Type: `method`

Copia campi, operazioni e impostazioni di un altro schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dello schema da cui ereditare. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Attende che l'altro schema sia dichiarato. I campi e le operazioni che lo schema ha già vengono mantenuti.

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

### schema.array()

Type: `method` · Since: `0.0.63`

Lo schema riceve un array di elementi invece di un solo oggetto.

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Ogni elemento viene convertito e validato. I dati che non sono un array diventano un array vuoto.

Example: Un array di elementi
```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`

Dichiara un'operazione con il suo input, la query, i parametri e i permessi in un solo oggetto.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'operazione, facoltativamente con parametri dell'URL (`read/{id:UID}`). Può essere omesso quando `options` ha `id` o `name`. |
| `options` | `Object` | yes |  | Opzioni dell'azione (vedi la tabella). |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

`input`, `query`, `params` e `output` accettano una dichiarazione inline (`'*name:String(50), email:Email, tags:[String], role:{admin|user}'`; `*` è obbligatorio, `@Name` è un altro schema o un'altra azione) oppure il nome di un JSON schema da `jsonschemas/`. Dati non validi fermano l'azione con un errore. Un nome come `'read/{id:UID}'` dichiara `params` a partire dal nome.

Opzioni:

| Opzione | Cosa fa |
| --- | --- |
| `action` | `function($, model)`: l'azione. Viene eseguita con lo schema come `this` |
| `name` | Una descrizione |
| `input` | Campi del corpo della richiesta; il risultato è in `model` |
| `output` | Campi della risposta |
| `query` | Campi della query string, in `$.query` (`filter` è un alias) |
| `params` | Campi dei parametri dell'URL, in `$.params` |
| `user` | `true`: solo un utente autenticato, altrimenti `401` |
| `sa` | `true`: solo un utente con `sa` o `su` |
| `permissions` | Una stringa o un array; l'utente ne ha bisogno di uno in `user.permissions` o `user.roles` (`sa`/`su` passano sempre) |
| `cache` | Mette in cache la risposta: `{ query, params, user, language, expire }`; `true` o un elenco di nomi di campi sceglie cosa forma la chiave della cache, `expire` è `'5 minutes'` per impostazione predefinita |
| `publish` | Pubblica l'input o l'output su TMS |

Una route chiama l'azione come qualsiasi altra operazione: `*Users --> create`.

Example: Azioni con input, query e permessi
```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: Route
```js
ROUTE('GET  /api/users/ *Users --> list');
ROUTE('POST /api/users/ *Users --> create');
```

Example: Mettere in cache la risposta per 10 minuti
```js
schema.action('stats', {
	query: 'year:Number',
	cache: { query: true, expire: '10 minutes' },
	action: function($) {
		// ...
	}
});
```

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

Type: `method`

Imposta l'operazione di salvataggio.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Usala quando una sola operazione sia crea sia aggiorna. Una route la chiama con `*Schema --> save`; dal codice usa `CALL('Schema --> save')`.

Example: Dichiararla e collegarla a una route
```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`

Imposta l'operazione di inserimento.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Il modello viene validato prima che l'operazione venga eseguita. Una route la chiama con `*Schema --> insert`; dal codice usa `CALL('Schema --> insert')`.

Example: Dichiararla e collegarla a una route
```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`

Imposta l'operazione di aggiornamento.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Viene validato l'intero modello; l'id di solito arriva dall'URL in `$.id`. Una route la chiama con `*Schema --> update`; dal codice usa `CALL('Schema --> update')`.

Example: Dichiararla e collegarla a una route
```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`

Imposta l'operazione patch, che modifica solo i campi inviati.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Solo i campi inviati vengono convertiti e validati, e i loro nomi sono in `$.keys`. Una route la chiama con `*Schema --> patch`; dal codice usa `CALL('Schema --> patch')`.

Example: Dichiararla e collegarla a una route
```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`

Imposta l'operazione di lettura. `schema.setGet()` è un alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Una route la chiama con `*Schema --> read` o `--> get`.

Example: Dichiararla e collegarla a una route
```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`

Imposta l'operazione query, che elenca gli elementi. `schema.setList()` è un alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Una route la chiama con `*Schema --> query` o `--> list`. Il `filter` converte la query string in `$.filter`.

Example: Un elenco con un filtro
```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`

Imposta l'operazione di rimozione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Una route la chiama con `*Schema --> remove`; dal codice usa `CALL('Schema --> remove')`.

Example: Dichiararla e collegarla a una route
```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`

Aggiunge un'operazione con un nome scelto da te. `schema.add()` è un alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'operazione. |
| `fn` | `Function|String` | yes |  | `function($, model)`, oppure `'Schema --> name'`. |
| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Al posto di una funzione puoi indicare `'Schema --> name'` per riutilizzare un'operazione di un altro schema.

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

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

Example: Riutilizzare un'operazione di un altro schema
```js
schema.addWorkflow('check', 'Common --> check');
```

### schema.middleware(fn)

Type: `method`

Aggiunge una funzione che viene eseguita prima di ogni operazione dello schema.

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

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Chiama `next()` per continuare. `next(true)` si ferma, quindi il middleware deve rispondere da sé, per esempio con `$.invalid()`. Più middleware vengono eseguiti nell'ordine in cui sono stati aggiunti.

Example: Solo per utenti autenticati
```js
schema.middleware(function($, next) {
	if ($.user)
		next();
	else {
		$.invalid(401);
		next(true);
	}
});
```

### schema.setResource(name)

Type: `method`

Imposta il file di risorse con i messaggi di errore dello schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del file di risorse in `resources/`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un campo senza un proprio messaggio legge da questa risorsa la chiave con il suo nome. `schema.setPrefix(prefix)` aggiunge un prefisso alle chiavi.

Example: Messaggi da una risorsa
```js
schema.setResource('errors');
schema.setPrefix('user_');
schema.define('email', 'Email', true); // key: user_email
```

### schema.setTimer(fn)

Type: `method` · Since: `0.0.63`

Imposta una funzione che viene eseguita ogni minuto. `schema.setService()` è un alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(counter)`; `counter` conta i minuti. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

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

### schema.setDestroy(fn)

Type: `method` · Since: `0.0.63`

Imposta una funzione che viene eseguita quando lo schema viene rimosso o sostituito.

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

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Example: Liberare risorse
```js
schema.setDestroy(function() {
	clearInterval(timer);
});
```

### $.callback([value])

Type: `method`

Termina l'operazione e risponde con un valore o con un errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|Error` | no |  | La risposta, oppure un errore. |

Un `Error` o un `ErrorBuilder` risponde con quell'errore. Funziona anche `$.callback(err, value)`, quindi puoi passare `$.callback` alle funzioni che richiamano con `(err, response)`. In un'operazione di schema, `$.callback()` senza valore risponde con il modello.

Example: Rispondere con dati
```js
schema.setQuery(function($) {
	NOSQL('users').find().callback($.callback);
});
```

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

Type: `method`

Termina l'operazione e risponde `{ "success": true, "value": ... }`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `success` | `Boolean` | no | `true` | Il risultato. |
| `value` | `Object` | no |  | Un valore inviato come `value`. |

Returns: `SchemaOptions` `$`.

Con un solo argomento che non è un booleano, quello è il valore. `$.success(false)` risponde `{ "success": false }`.

Example: Rispondere con il nuovo id
```js
$.success(model.id);
// { "success": true, "value": "1fd0b001ez51d" }
```

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

Type: `method`

Termina l'operazione con un errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Number|Error` | yes |  | Nome del campo, un messaggio, un codice di stato o un errore. |
| `message` | `String` | no |  | Il messaggio di errore. `@key` legge una risorsa. |

Returns: `SchemaOptions|Function` `$`, oppure una callback quando viene chiamato senza argomenti.

`$.invalid('email')` segnala un campo non valido con il suo messaggio predefinito, `$.invalid('email', 'Wrong email')` con il tuo messaggio, `$.invalid('Something went wrong')` un messaggio senza campo e `$.invalid(404)` un codice di stato. Sono accettati anche un `Error` o un `ErrorBuilder`. Senza argomenti restituisce una funzione `(err)` che termina l'operazione con quell'errore.

Example: Errori
```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`

Restituisce una callback `(err, response)` che termina l'operazione con un successo o con l'errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean|Object` | no |  | `true` per inviare la risposta, oppure un valore da inviare. |

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

`$.done()` risponde `{ "success": true }`, `$.done(true)` mette la risposta in `value` e `$.done(something)` mette `something` in `value`.

Example: Rispondere dopo una chiamata al database
```js
schema.setRemove(function($) {
	NOSQL('users').remove().where('id', $.id).callback($.done());
});
```

### $.successful(fn)

Type: `method`

Restituisce una callback che termina l'operazione in caso di errore e altrimenti esegue `fn`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(response)`, eseguita con `$` come `this`. |

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

Example: Continuare solo senza errori
```js
NOSQL('users').one().where('id', $.id).callback($.successful(function(user) {
	$.callback(user || {});
}));
```

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

Type: `method` · Since: `0.0.97`

Esegue una funzione con una callback in stile Node.js e restituisce una promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | Una funzione il cui ultimo argomento è `callback(err, response)`. |
| `a, b, c` | `Object` | no |  | Argomenti per `fn`. |

Returns: `Promise` Si risolve con la risposta.

Gli argomenti vengono passati a `fn` prima della callback. In caso di errore, l'operazione termina con quell'errore e la promise non viene mai risolta.

Example: Attendere una funzione con callback
```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`

Termina l'operazione e reindirizza la richiesta a un altro URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | L'URL di destinazione. |

Returns: `SchemaOptions` `$`.

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

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

Type: `method`

Esegue un'altra azione o operazione dall'interno di un'operazione, con lo stesso controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Operazione di questo schema, `Schema --> operation` oppure il nome di un'azione. |
| `model` | `Object` | no |  | Dati per l'operazione. |

Returns: `SchemaCall` Lo stesso oggetto di `CALL()`.

Un nome senza `-->` è un'operazione dello schema corrente. Un prefisso `+`, `-` o `#` imposta il metodo (POST, GET o PATCH). È `CALL()` legato alla richiesta corrente, quindi restituisce lo stesso oggetto con `.callback()` e `.promise()`.

Example: Chiamare un'altra operazione
```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`

Ascolta un evento dell'operazione: `error`, `response` o `end`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | `error`, `response` o `end`. |
| `fn` | `Function` | yes |  | Il listener. |

Returns: `SchemaOptions` `$`.

`error` riceve gli errori, `response` la risposta ed `end` entrambi `(err, response)`. Si attivano quando termina un'operazione di schema chiamata con una sola operazione.

Example: Registrare la fine di un'operazione
```js
$.on('end', function(err, response) {
	console.log('done', err, response);
});
```

### $.model

Type: `property`

Il modello validato dell'operazione.

Returns: `Object`

Contiene solo i campi dichiarati, convertiti nei loro tipi. Le operazioni lo ricevono anche come secondo argomento. `$.value` è un alias.

Example: Leggere il modello
```js
schema.setInsert(function($) {
	console.log($.model.name);
	$.success();
});
```

### $.query

Type: `property`

La query string della richiesta.

Returns: `Object`

In un'azione con l'opzione `query`, i campi vengono convertiti e validati.

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

### $.params

Type: `property`

I parametri dinamici dell'URL della route.

Returns: `Object`

In un'azione con l'opzione `params`, vengono convertiti e validati.

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

### $.id

Type: `property`

Il primo parametro dinamico dell'URL della route, di solito l'id.

Returns: `String`

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

### $.user

Type: `property`

L'utente autenticato della richiesta, oppure `null`.

Returns: `Object`

Le azioni con `user`, `sa` o `permissions` lo verificano prima di essere eseguite. `$.session` contiene la sessione.

Example: Salvare l'autore
```js
model.userid = $.user.id;
```

### $.keys

Type: `property`

In una richiesta `PATCH`, i nomi dei campi inviati; altrimenti `null`.

Returns: `Array`

Solo questi campi vengono convertiti e validati.

Example: Applicare patch solo ai campi inviati
```js
schema.setPatch(function($, model) {
	console.log($.keys); // ['name']
	NOSQL('users').modify(model).where('id', $.id);
	$.success();
});
```

### $.filter

Type: `property`

La query string convertita con il `filter` dell'operazione.

Returns: `Object`

Il filtro è il secondo argomento di `schema.setQuery()` e degli altri metodi set. Senza filtro è la query così come è arrivata.

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

### $.controller

Type: `property`

Il controller della richiesta, oppure niente quando l'operazione viene eseguita dal codice.

Returns: `Controller`

`$` legge anche alcune proprietà del controller direttamente: `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` e `$.sessionid`.

Example: Leggere la richiesta
```js
console.log($.ip, $.language, $.headers['user-agent']);
```

### $.responses

Type: `property`

Le risposte delle operazioni precedenti quando una route o `CALL()` ne esegue più di una.

Returns: `Object`

`$.response(name)` ne restituisce una.

Example: Usare il risultato di un'operazione precedente
```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`

Dichiara un'azione che non appartiene a uno schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'azione, per esempio `Users/create`. Può essere omesso quando `options` ha `id` o `name`. |
| `options` | `Object` | yes |  | Opzioni dell'azione. |

Returns: `Object` L'azione, con un metodo `remove()`.

Accetta le stesse opzioni di `schema.action()` (`action`, `name`, `input`, `output`, `query`, `params`, `user`, `sa`, `permissions`, `cache`, `publish`) e inoltre:

| Opzione | Cosa fa |
| --- | --- |
| `route` | `'API /api/'` dichiara una route API per l'azione. Il nome API è il nome dell'azione in minuscolo con `_` al posto di `/`, con `+` quando l'azione ha `input` e `-` altrimenti |
| `csrf`, `encrypt`, `compress` | Come `schema.csrf()`, `schema.encrypt()` e `schema.compress()` |

L'azione viene eseguita con `$` come `this`. Dichiarare un'azione con un nome già esistente la sostituisce, e `action.remove()` la rimuove insieme alla sua route. Una route chiama un'azione con `-->` e senza schema.

Example: Un'azione e la sua 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: Un'azione con la propria route API
```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`

Esegue azioni od operazioni di schema dal codice.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'azione o `Schema --> operations`, facoltativamente con un prefisso `+`, `-` o `#`. |
| `model` | `Object` | no |  | Dati per l'operazione. Vengono validati. |
| `controller` | `Controller|SchemaOptions` | no |  | La richiesta con cui eseguire, oppure un `$`. |

Returns: `SchemaCall` Un oggetto con i metodi della tabella.

`name` è un'azione (`Users/create`), più azioni separate da spazi, oppure `Schema --> operations`. Un prefisso `+`, `-` o `#` imposta il metodo (POST, GET o PATCH); senza prefisso, la chiamata è POST quando c'è un modello. La chiamata parte al tick successivo, quindi imposta prima le sue opzioni:

| Metodo | Cosa imposta |
| --- | --- |
| `.query(obj)`, `.params(obj)` | `$.query` e `$.params` |
| `.user(obj)`, `.language(str)` | `$.user` (o l'utente di un `$`) e la lingua |
| `.controller(ctrl)` | Il controller (o il controller di un `$`) |
| `.callback(fn)` | `function(err, response)` |
| `.done($, fn)` | Termina `$` in caso di errore, altrimenti esegue `fn(response)` |
| `.promise([$])` | Restituisce una promise; con `$`, un errore termina quell'operazione |
| `.debug()` | Stampa l'input e il risultato nella console |

Con più operazioni la risposta è un oggetto con il risultato di ciascuna.

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

Example: Attendere un'operazione di schema con await
```js
var users = await CALL('-Users --> list').query({ page: 1 }).promise();
```

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

Type: `method`

Esegue operazioni di schema dal codice. `$ACTION()` è un alias.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | `Schema --> operations` con un prefisso di metodo. |
| `model` | `Object` | no |  | Dati per l'operazione. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `controller` | `Controller|Object` | no |  | La richiesta, oppure un oggetto con `query`, `params`, `user`, `id`… |

Returns: `Promise` Una promise quando non c'è una callback.

`name` è `+Schema --> operations` (oppure `-`, `#`, o un metodo come `POST Schema --> insert`). Al posto di un controller puoi passare un oggetto con `query`, `params`, `user`, `session`, `body`, `headers` e `id`. Senza callback restituisce una promise. Per le azioni dichiarate con `NEWACTION()`, usa `CALL()`.

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

Example: Con una query e un utente
```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`

Converte e valida un modello con uno schema, senza eseguire alcuna operazione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Nome dello schema. |
| `model` | `Object` | yes |  | Dati da validare. |
| `callback` | `Function` | no |  | `function(err, model)`. |
| `novalidate` | `Boolean` | no | `false` | `true` si limita a convertire i dati. |
| `controller` | `Controller` | no |  | Un controller che riceve l'errore al posto della promise. |

Returns: `Promise` Il modello validato, quando non c'è una callback.

Senza callback restituisce una promise.

Example: Validare dati
```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`

Esegue dal codice un'operazione di uno schema, aggiunta con `schema.addOperation()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Il nome dello schema. |
| `name` | `String` | yes |  | Il nome indicato in `schema.addOperation()`. |
| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `controller` | `Controller|Object` | no |  | Il controller, oppure un oggetto `$`. |

Returns: `Boolean` `true` quando lo schema esiste.

`schema.addOperation(name, operation, [filter])` collega un nome nello schema a un'operazione globale dichiarata con `NEWOPERATION()`. `$OPERATION()` la esegue: lo schema chiama `OPERATION(operation, $.model, $.callback, schemaName, $)`, quindi l'operazione risponde attraverso lo schema e ne condivide il controller.

Il modello non viene preparato né validato: `$.model` è un oggetto vuoto, e le opzioni arrivano come `$.options`. I middleware dello schema vengono comunque eseguiti. Quando `options` è una funzione, è la callback. Uno schema mancante chiama la callback con l'errore `Schema "name" not found.`; uno schema senza l'operazione risponde con `Schema "name" doesn't contain "Operation.name" operation.`

Non confonderlo con `OPERATION()`, che esegue direttamente un'operazione globale.

Example: Collegare ed eseguire un'operazione
```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`

Esegue dal codice un task di uno schema, aggiunto con `schema.addTask()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Il nome dello schema. |
| `name` | `String` | yes |  | Il nome indicato in `schema.addTask()`. |
| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `controller` | `Controller|Object` | no |  | Il controller, oppure un oggetto `$`. |

Returns: `Boolean` `true` quando lo schema esiste.

`schema.addTask(name, task, [filter], [callback])` collega un nome nello schema a un passo di un task dichiarato con `NEWTASK()` (`task` è `'name/step'`). `$TASK()` lo esegue: lo schema avvia `TASK(task, $.callback, $)` con `$.model` come valore del task. Con la `callback` di `addTask()`, lo schema chiama invece `callback($, err, response)` e rispondi tu.

Il modello non viene preparato né validato: `$.model` è un oggetto vuoto, e le opzioni arrivano come `$.options`. Quando `options` è una funzione, è la callback. Uno schema mancante chiama la callback con l'errore `Schema "name" not found.`

Example: Collegare ed eseguire un 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`

Restituisce un oggetto con dati casuali che corrispondono a uno schema, per test e demo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String|Object` | yes |  | Il nome di uno schema, una dichiarazione inline o un oggetto di tipi. |
| `onlyrequired` | `Boolean` | no | `false` | Compila solo i campi obbligatori. |

Returns: `Object` Il modello fittizio.

`schema` è il nome di uno schema, una dichiarazione inline come `'name:String, email:Email'` o un oggetto come `{ id: UID, name: 'String(30)' }`. Ogni campo riceve un valore casuale del suo tipo: email, numeri di telefono, CAP, URL, identificatori (`UID`, `GUID`), numeri, date, booleani e stringhe (tagliate alla lunghezza dichiarata, al massimo 30 caratteri). Gli array ricevono due elementi, gli enum e gli elenchi chiave-valore uno dei loro valori, e i campi di un altro schema un oggetto fittizio annidato.

Alcuni nomi di campo danno valori realistici: `firstname`, `lastname`, `fullname`, `company`, `country`, `currency`, `language`, `age`, `birthdate`.

Con `onlyrequired` vengono compilati solo i campi obbligatori di uno schema con nome.

Example: Da uno 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`

Aggiunge un'estensione all'operazione `query`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `query` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `query`. Alias: `schema.setListExtension()`.

Example: Estendere un'operazione da un 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`

Aggiunge un'estensione all'operazione `read`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `read` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `read`. Alias: `schema.setGetExtension()`.

Example: Estendere un'operazione da un 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`

Aggiunge un'estensione all'operazione `insert`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `insert` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `insert`.

Example: Estendere un'operazione da un 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`

Aggiunge un'estensione all'operazione `update`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `update` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `update`.

Example: Estendere un'operazione da un 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`

Aggiunge un'estensione all'operazione `patch`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `patch` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `patch`.

Example: Estendere un'operazione da un 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`

Aggiunge un'estensione all'operazione `remove`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `remove` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `remove`.

Example: Estendere un'operazione da un 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`

Aggiunge un'estensione all'operazione `save`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `save` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `save`.

Example: Estendere un'operazione da un 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`

Aggiunge un'estensione a un workflow.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del workflow. |
| `fn` | `Function` | yes |  | `function($, data, next)`. `data` è il valore passato a `$.extend()`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Un'estensione è una funzione `function($, data, next)` che aggiungi a un workflow esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni allo stesso workflow. Alias: `schema.addExtension()`.

Example: Estendere un 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`

Esegue le estensioni dell'operazione corrente.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | Un valore passato a ogni estensione come secondo argomento. |
| `callback` | `Function` | no |  | Viene eseguita dopo l'ultima estensione. |

Returns: `Boolean` `true` quando esistono estensioni, altrimenti `undefined`.

Esegue le estensioni aggiunte con `schema.setSaveExtension()`, `schema.addWorkflowExtension()` e gli altri metodi per l'operazione in esecuzione. Senza `callback`, tutte le estensioni vengono eseguite insieme. Con `callback`, vengono eseguite una alla volta (ognuna chiama `next()`) e `callback` viene eseguita alla fine, anche quando non ci sono estensioni. Il metodo restituisce `true` quando l'operazione ha estensioni.

Example: Attendere le estensioni
```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`

Richiede un token CSRF valido per ogni route dello schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` la disattiva. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Le route dello schema funzionano allora come le route con il flag `csrf`: il token di `controller.csrf()` deve arrivare nell'header `x-csrf-token` o nell'argomento `?csrf=`. Un token non valido risponde con l'errore `Invalid CSRF token`.

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

### schema.encrypt([enable])

Type: `method`

Cifra le risposte delle route dello schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` la disattiva. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Le risposte testuali vengono cifrate con `CONF.secret_encryption` e ricevono l'header `X-Encryption: a`. Senza `secret_encryption` nella configurazione non viene cifrato nulla.

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

### schema.compress([enable])

Type: `method`

Esclude i valori `null` e `undefined` dalle risposte JSON dello schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` la disattiva. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

La risposta JSON delle route dello schema viene serializzata senza le chiavi il cui valore è `null` o `undefined`, quindi è più piccola.

Example: JSON più piccolo
```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`

Copia campi che lo schema non definisce.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `field` | `String|Array` | yes |  | Un nome, un elenco separato da virgole o un array di nomi. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

I campi elencati vengono copiati dall'input nel modello così come sono: senza conversione e senza validazione. Funziona anche una sola stringa con i nomi separati da virgole.

Example: Metadati liberi
```js
NEWSCHEMA('Events', function(schema) {
	schema.define('name', String, true);
	schema.allow('meta, tags');
});
```

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

Type: `method`

Aggiunge un controllo asincrono di un campo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del campo. |
| `fn` | `Function` | yes |  | `function($)`. |
| `cache` | `String` | no |  | Per quanto tempo viene mantenuto il risultato, per esempio `'10 minutes'`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Il controllo viene eseguito dopo la validazione, solo quando il campo ha un valore. `fn($)` riceve `$.value`, `$.model`, `$.name`, `$.user`, `$.query` e gli altri valori della richiesta. Chiama `$.next([value])` (o `$.success([value])`) per accettare il valore, facoltativamente con uno nuovo, oppure `$.invalid(error)` per rifiutarlo; un campo rifiutato viene impostato a `null`. Con `cache` (una scadenza come `'5 minutes'`) il risultato per lo stesso valore viene mantenuto in cache.

Example: Verificare un codice paese
```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`

Rimuove tutti i campi dello schema.

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Rimuove i campi definiti, i campi obbligatori, i controlli di `schema.verify()` e i campi di `schema.allow()`. Le operazioni restano.

Example: Definire di nuovo i campi
```js
GETSCHEMA('Products', function(err, schema) {
	schema.clear();
	schema.define('name', String, true);
});
```

### schema.setPrimary(name)

Type: `method`

Indica la chiave primaria dello schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del campo. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Il nome viene salvato in `schema.primary`, e `schema.inherit()` lo copia. Il framework non lo usa nelle operazioni: è un'informazione per il tuo codice.

Example: Una chiave primaria
```js
NEWSCHEMA('Users', function(schema) {
	schema.define('id', 'UID');
	schema.setPrimary('id');
});
```

### schema.setError(fn)

Type: `method`

Imposta una funzione che viene eseguita quando un'operazione o la validazione dello schema termina con errori.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(error, model, type, [name])`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

`fn(error, model, type, [name])` riceve l'`ErrorBuilder`, il modello, il tipo dell'operazione (`'make'` per la validazione, `'save'`, `'workflow'`, ...) e il nome di un workflow. Puoi leggere o modificare gli errori prima che vengano restituiti.

Example: Registrare l'input non valido
```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`

Aggiunge un'operazione dello schema che esegue un task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'operazione. |
| `task` | `String` | yes |  | Il task nella forma `'name/start'`. |
| `filter` | `String` | no |  | Campi della query string. |
| `callback` | `Function` | no |  | `function($, err, response)`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Chiamare l'operazione (per esempio `CALL('Schema --> name')` o `*Schema --> name` in una route) esegue `TASK(task)` con il modello come valore. La risposta del task è la risposta dell'operazione. Con `callback($, err, response)` rispondi tu.

Example: Un'operazione di schema che esegue un 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`

Aggiunge un'operazione dello schema che esegue un'operazione di `NEWOPERATION()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'operazione nello schema. |
| `operation` | `String` | yes |  | Il nome dell'operazione di `NEWOPERATION()`. |
| `filter` | `String` | no |  | Campi della query string. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Chiamare l'operazione dello schema (per esempio `*Schema --> name` in una route) esegue `OPERATION(operation)` con il modello come valore, e la sua risposta è la risposta dell'operazione dello schema.

Example: Riutilizzare un'operazione
```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`

Legge o sostituisce l'elenco dei valori di un campo enum.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del campo. |
| `value` | `Array|Object` | no |  | Un nuovo elenco di valori. |

Returns: `Array|Object` L'elenco corrente, oppure `undefined` per gli altri campi.

Funziona per i campi definiti con un array (enum) o con un oggetto (chiave-valore). Con `value` l'elenco viene sostituito.

Example: Valori caricati in seguito
```js
NEWSCHEMA('Tickets', function(schema) {
	schema.define('status', ['open', 'closed']);
});

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

### schema.props()

Type: `method`

Descrive i campi dello schema.

Returns: `Object` La descrizione dei campi.

Restituisce un oggetto con una chiave per campo e il suo `type` (`number`, `string`, `uid`, `email`, `boolean`, `date`, ...), più `required` e `length` quando sono impostati. Utile per descrivere lo schema a un client.

Example: Inviare i campi a un client
```js
function fields() {
	this.json(GETSCHEMA('Users').props());
}
```

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

Type: `method`

Prepara e valida un modello dal codice.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `model` | `Object` | yes |  | L'input. |
| `callback` | `Function` | no |  | `function(err, model)`. |

Returns: `Object` Il modello preparato (prima dei controlli asincroni).

Converte l'input secondo i campi dello schema, lo valida ed esegue i controlli di `schema.verify()`. `callback(err, model)` riceve l'`ErrorBuilder` o il modello preparato. Alias: `schema.load()`.

Example: Validare un valore
```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`

Valida un modello senza convertirlo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `model` | `Object` | yes |  | Il modello. |

Returns: `ErrorBuilder` Gli errori; `.is` è `true` quando ce ne sono.

Verifica i campi obbligatori e la validazione di ogni campo. Non esegue i controlli di `schema.verify()`.

Example: Verificare un modello
```js
var errors = GETSCHEMA('Users').validate({ name: '' });
if (errors.is)
	console.log(errors.items);
```

### schema.default()

Type: `method`

Crea un modello con i valori predefiniti dei campi.

Returns: `Object` Un nuovo modello.

Ogni campo riceve il suo valore predefinito: `0` per i numeri, `''` per le stringhe, `false` per i booleani, `NOW` per le date, `[]` per gli array e un modello predefinito per un campo di un altro schema. Alias: `schema.create()`.

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

### schema.destroy()

Type: `method`

Rimuove lo schema.

Returns: `undefined` Niente.

Lo schema viene rimosso dall'elenco degli schemi e viene eseguita la sua funzione di `schema.setDestroy()`.

Example: Rimuovere uno schema
```js
GETSCHEMA('Temporary').destroy();
```

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

Type: `method`

Esegue dal codice un workflow dello schema con un modello.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del workflow. |
| `model` | `Object` | yes |  | L'input. |
| `options` | `Object` | no |  | Un valore disponibile come `$.options`. |
| `callback` | `Function` | yes |  | `function(err, response)`. |
| `controller` | `Controller` | no |  | Un controller o un `$` da cui prendere l'utente e la richiesta. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

Il modello viene prima preparato e validato, come in una route. `schema.workflow2(name, [options], callback, [controller])` lo esegue senza modello e senza validazione. Per la maggior parte del codice `CALL()` ed `EXEC()` sono più semplici.

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

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

Type: `method`

Esegue l'operazione `query` dal codice.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no |  | Un valore disponibile come `$.options`. |
| `callback` | `Function` | yes |  | `function(err, response)`. |
| `controller` | `Controller` | no |  | Un controller o un `$`. |

Returns: `SchemaBuilderEntity` Lo schema, per il concatenamento.

`schema.read()` (alias `schema.get()`) e `schema.remove()` funzionano nello stesso modo per le operazioni `read` e `remove`. Queste vengono eseguite senza modello.

Example: Elencare dal codice
```js
GETSCHEMA('Products').query(function(err, items) {
	console.log(items);
});
```
