48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
const types = require('./types/index.js')
|
|
const BaseType = require('./types/base.js') // eslint-disable-line
|
|
const validator = {}
|
|
module.exports = validator
|
|
|
|
validator.Base = types.Base
|
|
validator.string = () => new types.StringType()
|
|
validator.number = () => new types.NumberType()
|
|
validator.boolean = () => new types.BooleanType()
|
|
validator.array = () => new types.ArrayType()
|
|
validator.object = () => new types.ObjectType()
|
|
|
|
/**
|
|
* @exports
|
|
* @typedef SchemaField
|
|
* @property {BaseType} type
|
|
* @property {SchemaField} children
|
|
*/
|
|
/**
|
|
* @exports
|
|
* @typedef {Object<string, SchemaField|BaseType>} Schema
|
|
*/
|
|
|
|
/**
|
|
* validate
|
|
* @param {Object} src
|
|
* @param {Schema} schema
|
|
*/
|
|
validator.validate = function (src, schema) {
|
|
if (typeof src !== 'object' || typeof schema !== 'object') throw new Error('source or schema not object')
|
|
|
|
for (const it in schema) {
|
|
if (schema[it] instanceof BaseType) {
|
|
const result = schema[it].validate(src[it])
|
|
if (result) throw new Error(`field [${it}]: ${result}`)
|
|
} else if (typeof schema[it] === 'object' && 'type' in schema[it] && schema[it].type instanceof BaseType) {
|
|
const result = schema[it].type.validate(src[it])
|
|
if (result) throw new Error(`field [${it}]: ${result}`)
|
|
} else {
|
|
throw new Error('not get any check schema type')
|
|
}
|
|
|
|
if (typeof schema[it] === 'object' && 'children' in schema[it]) {
|
|
validator.validate(src[it], schema[it].children)
|
|
}
|
|
}
|
|
}
|