akidee / schema.js

Sophisticated JSON schema based data validation and adaptation
MIT License
173 stars 13 forks source link

schema.js

Installation

npm install schema

API

Environment

The environment is a context, where your schemas and validations live in. You need to create an environment before creating your schemas to define some default settings that will affect all schemas created in this environment:

var myEnv = require('schema')('envIdentifier', options)

myEnv.Schema

Instances contain a JSON Schema:

var schema = myEnv.Schema.create({
    type: 'object',
    properties: {

        q: {
            type: 'string',
            minLength: 1,
            maxLength: 200,
            'default': '',
            fallbacks: {
                maxLength: 'truncateToMaxLength'
            }
        },

        hl: {
            type: 'string',
            enum: [ 'en', 'de', 'fr' ],
            'default': 'en',
            pre: function (value) {
                if (typeof value === 'object') return value;
                return String(value).toLowerCase();
            }
        },

        start: {
            type: 'integer',
            minimum: 0,
            maximum: 991,
            maximumCanEqual: false,
            'default': 0
        },

        order: {
            type: 'string',
            enum: [ 'name', 'date' ],
            'default': 'date'
        }
    },

    additionalProperties: false
})

Extensions

Still not supported

Irrelevant for validation

When writing a new schema, you can use the file PROPERTY_OVERVIEW_02 to get a quick overview over all supported properties.

myEnv.Validation

var validation = schema.validate({

    q: 'OK',
    start: -5,
    num: -100.99,
    xyz: 'additionalProperty'
})

var assert = require('assert')

assert.deepEqual(
    validation.instance,
    {
        q: 'OK',
        start: 0,
        order: 'date',
        hl: 'en'
    }
)

assert.strictEqual(
    validation.isError(),
    false
)

myEnv.f

With this little utility, you create a secure JavaScript function with an implicit schema.

Example: http://github.com/akidee/schema.js/blob/master/examples/myEnv.f.js

Dependencies