36 lines
932 B
JavaScript
36 lines
932 B
JavaScript
const Base = require('./base.js')
|
|
const util = require('util')
|
|
const validate = require('../validate.js')
|
|
|
|
/**
|
|
* @typedef {import('../type.js').Schema} Schema
|
|
*/
|
|
|
|
class TypeObject extends Base {
|
|
/**
|
|
* @param {Object<string, Schema>} child
|
|
*/
|
|
constructor (child) {
|
|
super()
|
|
if (child && typeof child !== 'object') throw new Error('child type wrong')
|
|
this._type = 'object'
|
|
this._child = child && Object.keys(child).length > 0 ? child : null
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
return null
|
|
}
|
|
}
|
|
module.exports = TypeObject
|