Spanish Total.js
English
Documentation For AI agents
Contents

JSON schemas

JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), the jsonschemas/ directory and the supported keywords.

.md GitHub
On this page

JSON schemas validate and convert data. They are loaded from jsonschemas/*.json and jsonschemas/*.txt files or declared with NEWJSONSCHEMA() and String.toJSONSchema(), and they are used by JSONSCHEMA(), by the input, output, params and query options of actions and by Total.js schemas.

Read the guide JSON schemas for the inline syntax, the supported keywords and examples.

API

method

JSONSCHEMA(schema, value, [callback], [error])

since 0.0.42 Validates and converts a value with a JSON schema.
ParameterTypeDescription
schema String|Object Name of a registered JSON schema, or a schema object
value Object Data to validate
callback? Function function(err, response); without it a promise is returned
error? ErrorBuilder An existing error builder to add the errors to Default: new ErrorBuilder()

Returns Promise|undefined A promise when no callback is given

schema is the name of a registered schema (a key of F.jsonschemas) or a schema object. The value is converted to the types of the schema and the properties that the schema does not declare are removed.

With a callback, it calls callback(err, response), where err is an ErrorBuilder or null. Without a callback, it returns a promise that resolves with the response or rejects with the ErrorBuilder. If the schema does not exist, the error is 404.

JSONSCHEMA() always validates all properties; for partial validation use the transform() method of the schema object.

Callback
JSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {
	if (err)
		console.log(err.items);
	else
		console.log(response.price); // 120.5
});
Promise
var model = await JSONSCHEMA('product', $.body);
method

NEWJSONSCHEMA(name, [declaration])

since 0.0.42 Registers or removes a JSON schema.
ParameterTypeDescription
name String|Object Name of the schema, or a schema object with $id
declaration? String Inline declaration such as 'name:String, *email:Email'; omit it to remove the schema
  • NEWJSONSCHEMA(object) registers a schema object under its $id.
  • NEWJSONSCHEMA(name, declaration) converts an inline declaration with String.toJSONSchema(name) and registers it under name.
  • NEWJSONSCHEMA(name) without a declaration removes the schema.

A schema object registered with NEWJSONSCHEMA(object) is stored as it is, without the transform() method. Use it with JSONSCHEMA(); for actions, prefer a file in jsonschemas/ or an inline declaration.

Inline declaration
NEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');
Remove
NEWJSONSCHEMA('Contact');
method

String.toJSONSchema([name], [url])

since 0.0.42 Converts an inline declaration to a JSON schema object.
ParameterTypeDescription
name? String Name to register the schema under; it is also used in $id
url? String Base URL of $id Default: CONF.url or https://schemas.totaljs.com/

Returns Object The JSON schema object

Parses name:Type pairs separated by commas or new lines and returns a JSON schema object with type: 'object', properties, required and a transform() method. With name, the schema is also registered in F.jsonschemas.

The $id is url + name + '.json'. The default URL is CONF.url, or https://schemas.totaljs.com/; without a name a hash of the declaration is used. $schema is https://json-schema.org/draft/2020-12/schema.

SyntaxResult
*name, !nameRequired property
name:String(50)maxLength: 50
name:[Type]Array of a type
name:{a|b|c}String enum (; works too)
name:{a:String, b:Number}Nested object
name:[{a:String}]Array of nested objects
name:@OtherAnother Total.js schema, JSON schema or action input

@Other throws an error if nothing with that name exists.

Nested objects and enums
var schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');
var res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });
method

jsonschema.transform(value, [partial], [error])

since 0.0.66 Validates a value with this schema object and returns the result synchronously.
ParameterTypeDescription
value Object Data to validate
partial? Boolean Validate only the properties present in the value Default: false
error? ErrorBuilder An existing error builder to add the errors to Default: new ErrorBuilder()

Returns Object { error: ErrorBuilder|null, response: Object }

Schema objects from jsonschemas/ files and from String.toJSONSchema() have this method. It returns { error, response }: error is an ErrorBuilder with the errors or null, and response is the converted value.

With partial, properties that are undefined in the value are skipped, so missing required properties are not errors. This applies at every level, also to the properties of nested objects.

Partial update
var schema = F.jsonschemas.product;
var res = schema.transform({ price: '99' }, true);
if (res.error)
	$.invalid(res.error);
else
	$.success();
property

F.jsonschemas

All registered JSON schemas, by name and by $id.

Returns Object Schema objects by key

An object with every registered schema. Files from jsonschemas/ are stored under their file name (and under $id for .json files), NEWJSONSCHEMA() and String.toJSONSchema(name) under the name, and converted Total.js schemas under the schema name and their $id.

Read a schema
var schema = F.jsonschemas.product;
console.log(Object.keys(schema.properties));
config

directory_jsonschemas : /jsonschemas/

since 0.0.42 The directory with JSON schema files.

Returns String Default /jsonschemas/

The framework reads .json and .txt files from this directory and its subdirectories when the application starts. Set the option to an empty value to disable loading.

config
directory_jsonschemas : /schemas/json/
method

PATH.jsonschemas([filename])

Returns the path to the JSON schemas directory or to a file in it.
ParameterTypeDescription
filename? String A file name

Returns String The path

Combines CONF.directory_jsonschemas with filename.

Read a file
var raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');
type

jsonschemas/{name}.json

since 0.0.42 A JSON schema in a JSON file.

A standard JSON schema object, read at start. It is registered under the file name without the extension (with the subdirectory, e.g. users/address) and under its $id. The framework adds the transform() method. An invalid file is reported as an error and skipped.

jsonschemas/user.json
{
	"$id": "https://example.com/user.json",
	"type": "object",
	"properties": {
		"name": { "type": "string", "subtype": "name", "maxLength": 50 },
		"email": { "type": "string", "subtype": "email" },
		"role": { "type": "string", "enum": ["admin", "user"] }
	},
	"required": ["name", "email"]
}
type

jsonschemas/{name}.txt

since 0.0.92 A JSON schema written in the inline syntax.

The content is converted with String.toJSONSchema() and registered under the file name without the extension. Write one property per line or separate them with commas.

jsonschemas/user.txt
*name:Name(50)
*email:Email
role:{admin|user}
tags:[String]
type

{ "type": "string", "subtype": "..." }

A string property, optionally with a subtype.

Values that are not strings are converted to strings; empty values become null. The subtype keyword adds formatting or a check: email, phone, url, zip, guid, uid, json, base64, color, icon, name, lower/lowercase, upper/uppercase, capitalize and capitalize2. String keywords: minLength, maxLength, enum.

JSON
{ "type": "string", "subtype": "email", "maxLength": 120 }
type

{ "type": "number" }

A number property; integer is accepted as a type name too.

Strings with digits are parsed with String.parseFloat(); other values become null. The smallint subtype allows -32767 to 32767 and tinyint 0 to 255. Number keywords: minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf. The value is not rounded, even for the int subtype.

JSON
{ "type": "number", "minimum": 1, "maximum": 100 }
type

{ "type": "boolean" }

A boolean property; bool is accepted too.

Values that are not booleans are parsed with String.parseBoolean().

JSON
{ "type": "boolean" }
type

{ "type": "date" }

A date property (a Total.js extension of JSON schema).

Values that are not Date objects are parsed with String.parseDate(). An invalid date becomes null; it is an error only when the property is required.

JSON
{ "type": "date" }
type

{ "type": "object", "properties": {...} }

An object property, validated by its own properties.

Only the declared properties are copied to the response. An object without properties is copied as it is. Object keywords: properties, required, minProperties, $ref.

JSON
{
	"type": "object",
	"properties": {
		"street": { "type": "string" },
		"city": { "type": "string" }
	},
	"required": ["city"]
}
type

{ "type": "array", "items": {...} }

An array property; each item is validated by items.

Without items the array is copied as it is (with duplicates removed when uniqueItems is set). Invalid items are left out and their errors are reported. Array keywords: items, minItems, uniqueItems.

JSON
{ "type": "array", "items": { "type": "string", "subtype": "email" }, "minItems": 1 }
property

"required": ["name", ...]

The list of required properties of an object.

A required property that is missing, empty or invalid is an error named after the property. In the inline syntax, start the name with * or !. With partial validation, missing properties are skipped.

JSON
{ "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] }
property

"properties": { ... }

The properties of an object and their schemas.

Each key is a property name and each value its schema. Properties that are not declared are removed from the response.

JSON
{ "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "number" } } }
property

"subtype": "email"

A Total.js keyword that adds a format check or a conversion to strings and numbers.

String subtypes: email, phone, url, zip, guid, uid, json, base64, color (#RGB, #RRGGBB, #RRGGBBAA), icon (Font Awesome or Total.js Icons classes), name, lower, lowercase, upper, uppercase, capitalize, capitalize2. Number subtypes with a check: smallint, tinyint. String.toJSONSchema() sets the subtype from the type name.

JSON
{ "type": "string", "subtype": "phone" }
property

"maxLength": 50

The maximum length of a string.

A longer string is an error. In the inline syntax, write String(50).

JSON
{ "type": "string", "maxLength": 50 }
property

"minLength": 3

The minimum length of a non-empty string.

A shorter string is an error. An empty value is checked only by required.

JSON
{ "type": "string", "minLength": 3 }
property

"enum": ["a", "b"]

The allowed values of a string.

A value that is not in the list is an error. An empty value is allowed unless the property is required. In the inline syntax, write {a|b}.

JSON
{ "type": "string", "enum": ["draft", "published"] }
property

"minimum": 1

The smallest allowed number.

A smaller number is an error.

JSON
{ "type": "number", "minimum": 1 }
property

"maximum": 100

The largest allowed number.

A larger number is an error.

JSON
{ "type": "number", "maximum": 100 }
property

"exclusiveMinimum": 0.5

The number must be greater than this value.

A number less than or equal to the value is an error.

JSON
{ "type": "number", "exclusiveMinimum": 0.5 }
property

"exclusiveMaximum": 10

The number must be smaller than this value.

A number greater than or equal to the value is an error.

JSON
{ "type": "number", "exclusiveMaximum": 10 }
property

"multipleOf": 5

The number must be a multiple of this value.

A number with a remainder is an error.

JSON
{ "type": "number", "multipleOf": 5 }
property

"items": { ... }

The schema of the items of an array.

Each item is validated by this schema; invalid items are left out and reported. The schema may be a simple type, an object with properties, or a $ref.

JSON
{ "type": "array", "items": { "type": "number" } }
property

"minItems": 1

The minimum number of valid items in an array.

Counted after invalid items are removed. An empty array of a required property is always an error.

JSON
{ "type": "array", "items": { "type": "string" }, "minItems": 1 }
property

"uniqueItems": true

Removes duplicate items from an array.

Duplicates are removed silently; they are not an error. Objects are compared by reference, so the option is useful for simple values.

JSON
{ "type": "array", "items": { "type": "string" }, "uniqueItems": true }
property

"minProperties": 1

The minimum number of valid properties in an object.

Counts the properties that end in the response.

JSON
{ "type": "object", "properties": { "a": { "type": "string" }, "b": { "type": "string" } }, "minProperties": 1 }
property

"$ref": "name"

Uses another registered JSON schema for a property.

A property without type and with $ref is validated by the schema F.jsonschemas[$ref]: the name of a file in jsonschemas/, a name from NEWJSONSCHEMA() or an $id. If the schema does not exist, it is an error. In the inline syntax, @Name embeds the other schema instead.

JSON
{ "type": "object", "properties": { "address": { "$ref": "address" } } }
method

schema.toJSONSchema()

Converts a Total.js schema to a JSON schema object.

Returns Object The JSON schema object

Converts the fields of the schema (and the fields from schema.jsonschema_define()) to properties and the required fields to required. The $id is CONF.url (or https://schemas.totaljs.com/) + the schema name + .json. The result is registered in F.jsonschemas under the schema name and the $id.

Export
var json = GETSCHEMA('Order').toJSONSchema();
console.log(JSON.stringify(json, null, '\t'));
method

schema.jsonschema_define(name, type, [required], [invalid])

since 0.0.42 Declares a field that appears only in the JSON schema made by schema.toJSONSchema().
ParameterTypeDescription
name String|Array Field name or names
type String|Object Field type as in schema.define(), or null to remove
required? Boolean Marks the field as required Default: false
invalid? String Error message Default: '@'

Returns Function A function that sets a default value and returns the schema

The field uses the same types as schema.define(), but it does not take part in the normal validation of the Total.js schema. type set to null removes the field. name may be an array of names. A string as the third argument is the error message and makes the field required.

Extra field
NEWSCHEMA('Order', function(schema) {
	schema.define('id', UID);
	schema.jsonschema_define('url', 'URL', true);
});
method

$MAKE(schema, model, [callback], [novalidate], [arg], [controller])

Makes and validates a model of a Total.js schema synchronously.
ParameterTypeDescription
schema String Name of the Total.js schema
model Object Data
callback? Function function(err, response, arg)
novalidate? Boolean Skip validation Default: false
arg? Object A value passed to the callback
controller? Controller|SchemaOptions Context of the request

Returns Object The made model

Calls schema.make() and returns the made model. Errors go to callback(err, response, arg). With novalidate, the model is converted but not validated. For a promise use MAKE() (see Schemas). Returns undefined if the schema does not exist.

Make
$MAKE('Order', $.body, function(err, model) {
	if (err)
		$.invalid(err);
	else
		$.success(model.id);
});
method

$CREATE(schema)

Creates a new model of a Total.js schema with default values.
ParameterTypeDescription
schema String Name of the Total.js schema

Returns Object|null A new model with default values

Returns the default object of the schema (schema.default()), or null if the schema does not exist. The defaults come from the fields of the Total.js schema.

Defaults
var order = $CREATE('Order');
Made in Europe