2020-06-03 15:49:04 +00:00
|
|
|
const Base = require('./base.js')
|
|
|
|
const util = require('util')
|
2020-06-10 13:32:50 +00:00
|
|
|
const validate = require('../validate.js')
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {import('../type.js').Schema} Schema
|
|
|
|
*/
|
2020-06-03 15:49:04 +00:00
|
|
|
|
|
|
|
class TypeObject extends Base {
|
2020-06-10 13:32:50 +00:00
|
|
|
/**
|
|
|
|
* @param {Object<string, Schema>} child
|
|
|
|
*/
|
|
|
|
constructor (child) {
|
2020-06-03 15:49:04 +00:00
|
|
|
super()
|
2020-06-10 13:32:50 +00:00
|
|
|
if (child && typeof child !== 'object') throw new Error('child type wrong')
|
2020-06-03 15:49:04 +00:00
|
|
|
this._type = 'object'
|
2020-06-10 13:32:50 +00:00
|
|
|
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}`
|
2020-06-10 13:32:50 +00:00
|
|
|
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
|