forked from joaquimserafim/express-validate-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (64 loc) · 1.88 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
eslint
no-multi-spaces: ["error", {exceptions: {"VariableDeclarator": true}}]
padded-blocks: ["error", {"classes": "always"}]
max-len: ["error", 80]
*/
'use strict'
const Joi = require('joi')
const apply = require('node-apply')
const between = require('between-range')
module.exports = ValidateSchema
function ValidateSchema (options) {
if (!(this instanceof ValidateSchema)) {
return new ValidateSchema(options)
}
this._options = options
}
ValidateSchema.prototype.query = function query (schema) {
return apply(procRequest, 'query', this._options, schema)
}
ValidateSchema.prototype.params = function params (schema) {
return apply(procRequest, 'params', this._options, schema)
}
ValidateSchema.prototype.body = function body (schema) {
return apply(procRequest, 'body', this._options, schema)
}
ValidateSchema.prototype.headers = function headers (schema) {
return apply(procRequest, 'headers', this._options, schema)
}
ValidateSchema.prototype.response = function response (schema) {
return apply(procResponse, this._options, schema)
}
//
// internal functions
//
function procRequest (type, options, schema, req, res, next) {
Joi.validate(req[type], schema, options, validateRequest)
function validateRequest (err, value) {
return err
? res.status(400).send(err.message)
: (req[type] = value) && next()
}
}
function procResponse (options, schema, req, res, next) {
res._json = res.json
res.json = jsonMethodOverride
function jsonMethodOverride (body) {
return isHttpError(res.statusCode)
? res._json(body)
: Joi.validate(body, schema, options, validateResponse)
function validateResponse (err) {
return err
? res.status(500).end(err.message)
: res._json(body)
}
}
next()
}
//
// supports official and unofficial code
//
function isHttpError (statusCode) {
return between(statusCode, 400, 599)
}