28 lines
917 B
JavaScript
28 lines
917 B
JavaScript
|
const BaseType = require('./types/base.js')
|
||
|
|
||
|
/**
|
||
|
* validate
|
||
|
* @param {Object} src
|
||
|
* @param {import('./type.js').Schema} schema
|
||
|
*/
|
||
|
function validate (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]) {
|
||
|
validate(src[it], schema[it].children)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = validate
|