forked from psvet/obey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject.js
65 lines (61 loc) · 2.18 KB
/
object.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import _ from 'lodash'
import rules from '../rules'
import Promise from 'bluebird'
/**
* Validates an object using the definition's `keys` property
* @param {Object} context An Obey type context
* @param {string} keyPrefix A prefix to include before the key in an error message
* @returns {Promise.<Object>} Resolves with the final object
*/
const validateByKeys = (context, keyPrefix) => {
// Build validation checks
const missingKeys = []
const promises = {}
_.forOwn(context.def.keys, (keyDef, key) => {
promises[key] = rules.validate(keyDef, context.value[key], context.def.opts, `${keyPrefix}${key}`, context.errors, false, context.initData)
.then(val => {
if (!context.value.hasOwnProperty(key) && val === undefined) missingKeys.push(key)
return val
})
})
// Check undefined keys
const strictMode = !context.def.hasOwnProperty('strict') || context.def.strict
_.forOwn(context.value, (val, key) => {
if (!context.def.keys[key]) {
if (strictMode) {
context.fail(`'${key}' is not an allowed property`)
} else {
promises[key] = val
}
}
})
return Promise.props(promises).then(obj => {
missingKeys.forEach(key => delete obj[key])
return obj
})
}
/**
* Validates an object using the definition's `values` property
* @param {Object} context An Obey type context
* @param {string} keyPrefix A prefix to include before the key in an error message
* @returns {Promise.<Object>} Resolves with the final object
*/
const validateByValues = (context, keyPrefix) => {
const promises = {}
_.forOwn(context.value, (val, key) => {
promises[key] = rules.validate(context.def.values, val, context.def.opts, `${keyPrefix}${key}`, context.errors, false, context.initData)
})
return Promise.props(promises)
}
const object = {
default: context => {
if (!_.isObject(context.value) || context.value === null) {
return context.fail('Value must be an object')
}
const prefix = context.key ? `${context.key}.` : ''
if (context.def.keys) return validateByKeys(context, prefix)
if (context.def.values) return validateByValues(context, prefix)
return context.value
}
}
export default object