typing
v0.1.9
Published
A type checking and JSON schema validation library
Downloads
775
Readme
typing.js
A simple and intuitive JSON schema validation library for JavaScript.
###Usage:
typing.check(<type-definition>, <data>);
###Example:
// import module
var typing = require('typing');
// import the built-in types
var int = typing.int;
var str = typing.str;
...
var tuple = typing.tuple;
var table = typing.table;
Define custom type with built-in types
// int(1): integer >= 1;
// str(1,50): string with length between 1 to 50;
// tuple: array with specified type and number of elements
var t_employee = tuple(int(1), str(1,50), tuple(str,str));
// matched
assert(typing.check(t_employee, [123, 'todd', ['1355-0011-107', 'CA 5607']]));
// not matched, id must be >= 1
assert(false == typing.check(t_employee, [0, 'todd', ['1355-0011-107', 'CA 5607']]));
Define custom type in JSON
// typing will do pattern matching based the type defined in JSON
// nullable : null or the wrapped type
// table: equivalent of array(tuple)
var t_response = {
status : {
code : int,
message : str
},
data : nullable(table(int(1), str(1,50), tuple(str,str)))
};
// matched
assert(typing.check(t_response, {
status : {
code : 200,
message : 'OK'
},
data : [
[1, 'Todd', ['1355-0011-107', 'CA 5607']],
[2, 'April', ['1582-0011-108', 'CA 5607']],
[3, 'Rex', ['1522-1011-138', 'CA 1008']]
]
});
// matched
assert(typing.check(t_response, {
status : {
code : 404,
message : 'NOT FOUND'
}
});
// not matched, status.message is missing
assert(typing.check(t_response, {
status : {
code : 300
}
});