validator/types/object.js
Jay 46b19757bd
All checks were successful
continuous-integration/drone/push Build is passing
[feat] add string type pattern check, add object child check
2020-06-10 13:32:50 +00:00

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