JSON schemas
JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), the jsonschemas/ directory and the supported keywords.
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.
JSONSCHEMA(schema, value, [callback], [error])| Parameter | Type | Description |
|---|---|---|
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.
JSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {
if (err)
console.log(err.items);
else
console.log(response.price); // 120.5
});
var model = await JSONSCHEMA('product', $.body);
method
NEWJSONSCHEMA(name, [declaration])
since 0.0.42
Registers or removes a JSON schema.
NEWJSONSCHEMA(name, [declaration])| Parameter | Type | Description |
|---|---|---|
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 withString.toJSONSchema(name)and registers it undername.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.
NEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');
NEWJSONSCHEMA('Contact');
method
String.toJSONSchema([name], [url])
since 0.0.42
Converts an inline declaration to a JSON schema object.
String.toJSONSchema([name], [url])| Parameter | Type | Description |
|---|---|---|
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.
| Syntax | Result |
|---|---|
*name, !name | Required 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:@Other | Another Total.js schema, JSON schema or action input |
@Other throws an error if nothing with that name exists.
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.
jsonschema.transform(value, [partial], [error])| Parameter | Type | Description |
|---|---|---|
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.
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.
F.jsonschemasReturns 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.
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.
directory_jsonschemas : /jsonschemas/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.
directory_jsonschemas : /schemas/json/
method
PATH.jsonschemas([filename])
Returns the path to the JSON schemas directory or to a file in it.
PATH.jsonschemas([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name |
Returns String The path
Combines CONF.directory_jsonschemas with filename.
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.
jsonschemas/{name}.jsonA 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.
{
"$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.
jsonschemas/{name}.txtThe 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.
*name:Name(50)
*email:Email
role:{admin|user}
tags:[String]
type
{ "type": "string", "subtype": "..." }
A string property, optionally with a subtype.
{ "type": "string", "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.
{ "type": "string", "subtype": "email", "maxLength": 120 }
type
{ "type": "number" }
A number property; integer is accepted as a type name too.
{ "type": "number" }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.
{ "type": "number", "minimum": 1, "maximum": 100 }
type
{ "type": "boolean" }
A boolean property; bool is accepted too.
{ "type": "boolean" }Values that are not booleans are parsed with String.parseBoolean().
{ "type": "boolean" }
type
{ "type": "date" }
A date property (a Total.js extension of JSON schema).
{ "type": "date" }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.
{ "type": "date" }
type
{ "type": "object", "properties": {...} }
An object property, validated by its own properties.
{ "type": "object", "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.
{
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" }
},
"required": ["city"]
}
type
{ "type": "array", "items": {...} }
An array property; each item is validated by items.
{ "type": "array", "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.
{ "type": "array", "items": { "type": "string", "subtype": "email" }, "minItems": 1 }
property
"required": ["name", ...]
The list of required properties of an object.
"required": ["name", ...]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.
{ "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] }
property
"properties": { ... }
The properties of an object and their schemas.
"properties": { ... }Each key is a property name and each value its schema. Properties that are not declared are removed from the response.
{ "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.
"subtype": "email"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.
{ "type": "string", "subtype": "phone" }
property
"maxLength": 50
The maximum length of a string.
"maxLength": 50A longer string is an error. In the inline syntax, write String(50).
{ "type": "string", "maxLength": 50 }
property
"minLength": 3
The minimum length of a non-empty string.
"minLength": 3A shorter string is an error. An empty value is checked only by required.
{ "type": "string", "minLength": 3 }
property
"enum": ["a", "b"]
The allowed values of a string.
"enum": ["a", "b"]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}.
{ "type": "string", "enum": ["draft", "published"] }
property
"minimum": 1
The smallest allowed number.
"minimum": 1A smaller number is an error.
{ "type": "number", "minimum": 1 }
property
"maximum": 100
The largest allowed number.
"maximum": 100A larger number is an error.
{ "type": "number", "maximum": 100 }
property
"exclusiveMinimum": 0.5
The number must be greater than this value.
"exclusiveMinimum": 0.5A number less than or equal to the value is an error.
{ "type": "number", "exclusiveMinimum": 0.5 }
property
"exclusiveMaximum": 10
The number must be smaller than this value.
"exclusiveMaximum": 10A number greater than or equal to the value is an error.
{ "type": "number", "exclusiveMaximum": 10 }
property
"multipleOf": 5
The number must be a multiple of this value.
"multipleOf": 5A number with a remainder is an error.
{ "type": "number", "multipleOf": 5 }
property
"items": { ... }
The schema of the items of an array.
"items": { ... }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.
{ "type": "array", "items": { "type": "number" } }
property
"minItems": 1
The minimum number of valid items in an array.
"minItems": 1Counted after invalid items are removed. An empty array of a required property is always an error.
{ "type": "array", "items": { "type": "string" }, "minItems": 1 }
property
"uniqueItems": true
Removes duplicate items from an array.
"uniqueItems": trueDuplicates are removed silently; they are not an error. Objects are compared by reference, so the option is useful for simple values.
{ "type": "array", "items": { "type": "string" }, "uniqueItems": true }
property
"minProperties": 1
The minimum number of valid properties in an object.
"minProperties": 1Counts the properties that end in the response.
{ "type": "object", "properties": { "a": { "type": "string" }, "b": { "type": "string" } }, "minProperties": 1 }
property
"$ref": "name"
Uses another registered JSON schema for a property.
"$ref": "name"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.
{ "type": "object", "properties": { "address": { "$ref": "address" } } }
method
schema.toJSONSchema()
Converts a Total.js schema to a JSON schema object.
schema.toJSONSchema()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.
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().
schema.jsonschema_define(name, type, [required], [invalid])| Parameter | Type | Description |
|---|---|---|
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.
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.
$MAKE(schema, model, [callback], [novalidate], [arg], [controller])| Parameter | Type | Description |
|---|---|---|
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('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.
$CREATE(schema)| Parameter | Type | Description |
|---|---|---|
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.
var order = $CREATE('Order');