Spanish Total.js
English
Documentation For AI agents
Contents

JSON schemas

Validate and convert data with JSON schemas: files in jsonschemas/, inline declarations and actions.

.md GitHub
On this page

A JSON schema describes the shape of a JSON object: its properties, their types and the rules they must follow. Total.js 4 uses JSON schemas to validate and convert data: it reads a value, converts each property to its type, drops the properties that the schema does not know, and returns the errors.

NEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number');

JSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) {
    // err === null
    // response === { name: 'Peter', email: 'peter@example.com', age: 33 }
});

A schema can come from three places: a .json file, a .txt file with the inline syntax, or code (NEWJSONSCHEMA() and String.toJSONSchema()). All of them are kept in F.jsonschemas under their name.

The jsonschemas/ directory

At start the framework reads the /jsonschemas/ directory (the directory_jsonschemas option), with its subdirectories:

FileHow it is read
jsonschemas/*.jsonA standard JSON schema object, parsed as JSON
jsonschemas/*.txtThe inline syntax (see below), converted with String.toJSONSchema()

The name of a schema is the file name without the extension (jsonschemas/users/address.json gives users/address). A .json schema with an $id is also registered under its $id. Files whose names start with . or end with -bk/_bk are skipped. Packages read their own jsonschemas/ directory.

{
    "$id": "https://example.com/product.json",
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
        "name": { "type": "string", "maxLength": 100 },
        "price": { "type": "number", "minimum": 0.01 },
        "tags": { "type": "array", "items": { "type": "string" }, "uniqueItems": true }
    },
    "required": ["name", "price"]
}

A similar schema as jsonschemas/product.txt, one property per line (or separated by commas):

*name:String(100)
*price:Number
tags:[String]

The inline syntax

String.toJSONSchema(), NEWJSONSCHEMA(name, string), .txt files and the input, output, params and query options of actions share one syntax: name:Type pairs separated by commas or new lines.

SyntaxResult
nameA string (the default type)
*name or !nameA required property
name:String(50)A string with maxLength: 50
tags:[String]An array of strings; works with any simple type
role:{admin|user}A string enum; ; also separates the values
address:{street:String, city:String}A nested object
items:[{name:String, qty:Number}]An array of nested objects
owner:@UserAnother schema: a Total.js schema, a JSON schema or the input of an action, looked up in this order

Type names are not case-sensitive. The string types are String, UID, GUID, Email, Phone, Name, URL, ZIP, Lower/Lowercase, Upper/Uppercase, Capitalize, Capitalize2, Color, Icon and Base64; each becomes type: 'string' with a subtype. The number types are Number, Number2, Float, Decimal, Int/Integer, SmallInt and TinyInt; each becomes type: 'number' with a subtype. The other types are Boolean (or Bool), Date and Object. An unknown type gives a string.

Validating data

JSONSCHEMA(name, value, [callback], [error]) validates a value against a registered schema. Without a callback it returns a promise. An unknown schema gives the error 404.

async function create() {
    var $ = this;
    try {
        var model = await JSONSCHEMA('product', $.body);
        // model is clean
        $.success();
    } catch (err) {
        $.invalid(err);
    }
}

Every schema object that the framework creates (files and String.toJSONSchema()) also has a transform(value, [partial], [error]) method. It returns { error, response } synchronously, where error is an ErrorBuilder or null:

var schema = 'name:String, *email:Email'.toJSONSchema('newsletter');
var res = schema.transform({ email: 'info@example.com' });
// res.error === null, res.response.email === 'info@example.com'

With partial set to true, only the properties present in the value are validated, so a missing required property is not an error. Use it for updates.

What validation does

  • Strings: other values are converted to strings. email and phone remove spaces (and email is lower-cased) and check the format; url, zip, guid, uid, base64, color and icon check the format; name normalizes a person's name; lower, upper, capitalize and capitalize2 change the case. An empty uid or guid becomes null.
  • Numbers: a string with digits is parsed with String.parseFloat(). smallint must be between -32767 and 32767, tinyint between 0 and 255.
  • Booleans: strings are parsed with String.parseBoolean().
  • Dates: other values are parsed with String.parseDate(); an invalid date becomes null.
  • Objects: only the declared properties are copied. An object without properties is copied as it is.
  • Arrays: each item is checked by items; invalid items are left out and reported.

An empty or invalid value of a required property is an error named after the property. Validation does not stop at the first error: all errors are collected.

JSON schemas in actions

The input, output, params and query options of schema.action() and NEWACTION() take an inline declaration (any string with ,, : or *) or the name of a registered JSON schema (a .json suffix is removed). See Schemas.

NEWACTION('Products/create', {
    name: 'Create a product',
    input: '*name:String(100), *price:Number, tags:[String]',
    action: function($, model) {
        // model is validated and converted
        $.success();
    }
});

NEWACTION('Products/update', {
    input: 'product', // jsonschemas/product.json
    action: function($, model) {
        $.success();
    }
});
  • input validates the model. It is validated as partial for PATCH requests and for actions marked with # in a route.
  • query and params validate $.query and $.params; their error names get the query. and params. prefix.
  • output converts the response of the action: properties that the schema does not declare are removed. Its errors are ignored.

Total.js schemas and JSON schemas

A Total.js schema (NEWSCHEMA()) can be converted to a JSON schema with schema.toJSONSchema(). The result is registered under the schema name, so actions, JSONSCHEMA() and @Name in inline declarations can use it. schema.jsonschema_define() adds fields that exist only in the converted JSON schema.

NEWSCHEMA('Order', function(schema) {
    schema.define('id', UID, true);
    schema.define('total', Number);
});

ON('ready', function() {
    GETSCHEMA('Order').toJSONSchema();
    JSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log);
});

$CREATE() and $MAKE() work with the Total.js schema itself: $CREATE() returns a model with default values and $MAKE() makes and validates a model synchronously.

The Total.js Message Service functions NEWPUBLISH(), NEWSUBSCRIBE() and NEWCALL() take the same forms: an inline declaration, a schema name or a schema object.

Made in Europe