0.0.14 • Published 3 years ago

@sa0001/api-validator v0.0.14

Weekly downloads
121
License
MIT
Repository
-
Last release
3 years ago

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 null can 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, isArray
  • bool, boolean, isBoolean
  • num, number, isNumber
  • obj, object, isObject
  • str, string, isString
  • any, 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)
  • isRound
  • isLower, isLowerCase
  • isUpper, isUpperCase
  • isTrim, 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
0.0.14

3 years ago

0.0.13

3 years ago

0.0.11

4 years ago

0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago