0.0.14 • Published 5 years ago
@sa0001/api-validator v0.0.14
API-Validator
API-Validator is a library designed for validating input/output of API methods, with a very powerful but compact syntax.
Simple Usage
A line of code is worth a thousand words. Here's a carefully curated minimal example of a validator schema, and both passing and failing input.
var ApiValidator = require('@sa0001/api-validator')
var validator = ApiValidator.new() // use default options
var schema = validator.schema({obj:1,schema:{
a: {int:1},
}})
var goodInput = {
a: 1,
}
var badInput = {
a: true,
}
// passing
result = schema.test(goodInput)
// failing
try {
result = schema.test(badInput)
catch (err) {
err
}
var output = ApiValidator.new().schema(schema).input(input).test()Guiding Principles
- the primary purpose of this library is for validating API input/output in JSON format, so don't count on values other than the following to be preserved: -- boolean -- number -- string -- array -- plain object
- all other types of value, including errors, symbols, may not be preserved
- only
nullcan be JSON-stringified, so all the following values are considered the same as null: --undefined,null,"",NaN,Infinity,-Infinity
Concepts
Simple Types: these are...
arr,array,isArraybool,boolean,isBooleannum,number,isNumberobj,object,isObjectstr,string,isStringany,mix,mixed-- allows any type of value, however most operators cannot be used
Complex Types: these are...
int,integer,isInteger
Operators: these are...
trim,toTrim,strip,toStrip(for Ruby lovers)isRoundisLower,isLowerCaseisUpper,isUpperCaseisTrim,isTrimmed,isStripped(for Ruby lovers)
Descriptors: these are...
Example
# example: sorted & unique array of enum values
{arr:1,sort:1,uniq:1,vals:{str:1,in:SomeEnum}}
# example: array of lat/lon
{arr:1,schema:[
{num:1,isRound:8,btw:[-90,90]}
{num:1,isRound:8,btw:[-180,180]}
]}
# example: object of lat/lon
{obj:1,schema:{
lat: {num:1,isRound:8,btw:[-90,90]}
lon: {num:1,isRound:8,btw:[-180,180]}
}}
# example: object of sorters (col -> dir)
{obj:1,keys:{str:1,regex:/^[\w]+$/},vals:{str:1,in:['ASC','DESC']}}TODO
- operator: compact
- operator: filter
- operator: reject