validator/types/object.js

36 lines
932 B
JavaScript
Raw Normal View History

2020-06-03 15:49:04 +00:00
const Base = require('./base.js')
const util = require('util')
const validate = require('../validate.js')
/**
* @typedef {import('../type.js').Schema} Schema
*/
2020-06-03 15:49:04 +00:00
class TypeObject extends Base {
/**
* @param {Object<string, Schema>} child
*/
constructor (child) {
2020-06-03 15:49:04 +00:00
super()
if (child && typeof child !== 'object') throw new Error('child type wrong')
2020-06-03 15:49:04 +00:00
this._type = 'object'
this._child = child && Object.keys(child).length > 0 ? child : null
2020-06-03 15:49:04 +00:00
}
validate (value) {
if (value === undefined && this._required) return `required`
if (value === undefined) return null
/* eslint-disable-next-line */
if (typeof value !== this._type) return `${util.inspect(value, false, null)} type not ${this._type}`
if (this._child !== null) {
try {
validate(value, this._child)
} catch (err) {
return err.message
}
}
2020-06-03 15:49:04 +00:00
return null
}
}
module.exports = TypeObject