forked from badges/shields
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.js
51 lines (47 loc) · 1.22 KB
/
validate.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
import emojic from 'emojic'
import Joi from 'joi'
import trace from './trace.js'
function validate(
{
ErrorClass,
prettyErrorMessage = 'data does not match schema',
includeKeys = false,
traceErrorMessage = 'Data did not match schema',
traceSuccessMessage = 'Data after validation',
allowAndStripUnknownKeys = true,
},
data,
schema
) {
if (!schema || !Joi.isSchema(schema)) {
throw Error('A Joi schema is required')
}
const options = { abortEarly: false }
if (allowAndStripUnknownKeys) {
options.allowUnknown = true
options.stripUnknown = true
}
const { error, value } = schema.validate(data, options)
if (error) {
trace.logTrace(
'validate',
emojic.womanShrugging,
traceErrorMessage,
error.message
)
let prettyMessage = prettyErrorMessage
if (includeKeys) {
const keys = error.details.map(({ path }) => path)
if (keys) {
prettyMessage = `${prettyErrorMessage}: ${keys.join(', ')}`
}
}
throw new ErrorClass({ prettyMessage, underlyingError: error })
} else {
trace.logTrace('validate', emojic.bathtub, traceSuccessMessage, value, {
deep: true,
})
return value
}
}
export default validate