-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (37 loc) · 945 Bytes
/
index.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
const Joi = require('joi')
class VerificationError extends Error {
constructor (options) {
super('Invalid Request Format Error')
const { message, path } = options
this.message = message
this.path = path
}
get [Symbol.toStringTag] () {
return 'VerificationError'
}
}
exports = module.exports = function verification (schema) {
return function (req, res, next) {
if (!schema) {
next()
}
const condition = {}
const verificationObj = {}
Object.keys(schema).forEach(key => {
const item = schema[key]
const requestObj = req[key]
for (let k in item) {
condition[k] = item[k]
verificationObj[k] = requestObj[k]
}
})
const s = Joi.object().keys(condition)
const result = Joi.validate(verificationObj, s)
const { error } = result
if (error) {
next(new VerificationError(error.details[0]))
} else {
next()
}
}
}