-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
184 lines (163 loc) · 6.6 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/**
* Created by E.Z.Moghaddam ([email protected])
*/
'use strict';
var _ = require('lodash');
var JOI = require('joi');
/**
* Default error formatter which given an errors array (returned by calling the validate method of underlying JOI
* framework) and generates a JSON representation of errors in following format:
*
* {
* code: 'VALIDATION_ERROR',
* message: 'Invalid data specified at request',
* errors: [
* {
* "message":"username is required",
* "type":"any.required",
* "path":"username"
* },
* {
* "message":"password is required",
* "type":"any.required",
* "path":"password"
* },
* {
* "message":"address is required",
* "type":"any.required",
* "path":"address"
* }
* ]
* }
*
* The application can override this method while initializing the valid-express module in order to generate error
* results in appropriate format
*
* @param {Array} errors Collection of error objects returned from calling validate method of underlying JOI
* framework
*
* @return {Object} JSON object containing formatted error report
*/
var validExpressDefaultErrorFormatter = function(errors){
return {
code: 'VALIDATION_ERROR',
message: 'Invalid data specified at request',
errors: _.map(errors, function(errorItem){
return {
message: errorItem.message,
type: errorItem.type,
path: errorItem.path
};
})
};
};
// Default options that would be used as 'options' parameters while calling joi.validate function
var joiOptions = {
abortEarly: false,
convert: true,
allowUnknown: false,
language: {},
presence: 'optional'
};
var validExpressOptions = {
errorFormatter: validExpressDefaultErrorFormatter
}
/**
* The validate function would be called in any url handler methods in order to validate parameters and generate
*
* @param schema An object containing joi validation options and joi validation schema to validate data against it.
* The provided schema option can specify the validation options as 'params', 'query' or 'body'
* attribute to validate corresponding parameters against it. Also JOI validation options can be
* passed as another property named 'options'. As an example, to validate parameters in 'query' and
* 'body' part of the request, the validate object should be called with a schema object like this:
*
* validate({
* query: {
* name: joi.string().required(),
* family: joi.string().required()
* },
* body: {
* age: joi.number().min(10).max(20).optional()
* }
* })
* @returns {Function} An express middleware function to validate request parameters
*/
var validate = function(schema){
// Override those options specified when calling validate function. The caller can specify joi validation options
// when calling the validate method by passing a specific 'options' property as part of their schema definition
var joiValidationOptions = joiOptions;
var validExpressValidationOptions = validExpressOptions;
if(schema.options){
joiValidationOptions = _.defaults(schema.options, joiOptions);
validExpressValidationOptions = _.defaults(schema.options, validExpressOptions);
if(_.has(joiValidationOptions, 'errorFormatter')) {
// Remove non-joi options from joiOptions object to prevent "unknown key" error in joi
joiValidationOptions = _.omit(joiValidationOptions, 'errorFormatter');
}
}
var paramsSchema = schema.params ? schema.params : null;
var querySchema = schema.query ? schema.query : null;
var bodySchema = schema.body ? schema.body : null;
var allSchema = (!schema.params && !schema.body && !schema.query) ? schema : null;
// delete allSchema.options;
var validateExpressImpl = function(req, res, next){
var errors = [];
var results = null;
if(allSchema){
var allValues = _.apply(req.params, req.query, req.body);
results = JOI.validate(allValues, allSchema, joiValidationOptions);
if(results.error){
errors.push(results.error.details);
}
} else {
if(paramsSchema){
results = JOI.validate(req.params, paramsSchema, joiValidationOptions);
if(results.error){
errors = errors.concat(results.error.details);
results = null;
}
}
if(!joiValidationOptions.abortEarly || (joiValidationOptions.abortEarly && errors.length === 0)) {
if(querySchema){
results = JOI.validate(req.query, querySchema, joiValidationOptions);
if(results.error){
errors = errors.concat(results.error.details);
results = null;
}
}
}
if(!joiValidationOptions.abortEarly || (joiValidationOptions.abortEarly && errors.length === 0)) {
if (bodySchema) {
if(req.body === undefined){
throw Error('req.body is undefined. Seems you have forgotten to include the body-parser ' +
'middleware in your express app');
}
results = JOI.validate(req.body, bodySchema, joiValidationOptions);
if (results.error) {
errors = errors.concat(results.error.details);
results = null;
}
}
}
}
if(errors.length > 0){
res.status(400).json(validExpressValidationOptions.errorFormatter(errors)).end();
} else {
return next();
}
};
return validateExpressImpl;
};
module.exports = function(options){
if(options){
joiOptions = _.defaults(options, joiOptions);
validExpressOptions = _.defaults(options, validExpressOptions);
if(_.has(joiOptions, 'errorFormatter')) {
// Remove non-joi options from joiOptions object to prevent "unknown key" error in joi
joiOptions = _.omit(joiOptions, 'errorFormatter');
}
}
return {
validate: validate
};
};