UNPKG

907 BJavaScriptView Raw
1'use strict'
2
3function parseProperty (name, value) {
4 let types
5 const { defaultValue } = value
6 if (typeof value === 'string') {
7 types = [value]
8 } else if (Array.isArray(value)) {
9 types = value
10 } else {
11 types = value.types || [value.type || 'string']
12 }
13 return { name, types, defaultValue }
14}
15
16function validate (property, object, value = property.defaultValue) {
17 const { name, types } = property
18 if (value === undefined) {
19 throw new Error(`Missing property ${name}`)
20 }
21 const valueType = typeof value
22 if (!types.includes(valueType)) {
23 throw new Error(`Invalid type of property ${name}`)
24 }
25 object[property.name] = value
26}
27
28module.exports = {
29 parse (schema) {
30 return Object.keys(schema).map(name => parseProperty(name, schema[name]))
31 },
32
33 validate (schema, object) {
34 schema.forEach(property => validate(property, object, object[property.name]))
35 }
36}