-
Notifications
You must be signed in to change notification settings - Fork 1
/
sanitize.js
55 lines (44 loc) · 1.2 KB
/
sanitize.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
const errors = require('./errors/')
function sanitize(provider) {
return options => sanitize.wrapper(provider, options)
}
sanitize.wrapper = (provider, options) => {
const required_fields = sanitize.sanitizeMandatory(provider, options)
if(required_fields.length > 0)
throw errors.MANDATORY(required_fields)
const validation = sanitize.sanitizeValidate(provider, options)
if(validation.errors.length > 0)
throw errors.VALIDATION(validation.errors)
return provider(options, validation.valids)
}
sanitize.sanitizeMandatory = (provider, options) => {
const keys = Object.keys(options)
return provider.contract.mandatory.filter(mandatory_field =>
!~keys.indexOf(mandatory_field)
)
}
sanitize.sanitizeValidate = (provider, options) => {
const errors = []
, valids = {}
Object.keys(provider.contract.validate).forEach(field => {
try {
valids[field] = provider.contract.validate[field](
options[field],
field in options,
options,
valids
)
} catch(error) {
errors.push({
field: field,
value: options[field],
error
})
}
})
return {
errors,
valids
}
}
module.exports = sanitize