forked from naz/swagger-express-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
265 lines (235 loc) · 6.81 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
const _ = require('lodash');
const debug = require('debug')('swagger-validator');
const Ajv = require('ajv');
const util = require('util');
const parseUrl = require('url').parse;
const pathToRegexp = require('path-to-regexp');
const valueValidator = require('validator');
let pathObjects = [];
let options = {};
const buildPathObjects = paths => _.map(paths, (pathDef, path) => ({
definition: _.get(options.schema, ['paths', path]),
original: ['paths', path],
regexp: pathToRegexp(path.replace(/\{/g, ':').replace(/\}/g, '')),
path,
pathDef,
}));
const matchUrlWithSchema = (reqUrl) => {
let url = parseUrl(reqUrl).pathname;
if (options.schema.basePath) {
url = url.replace(options.schema.basePath, '');
}
const pathObj = pathObjects.filter(obj => url.match(obj.regexp));
let match = null;
if (pathObj[0]) {
match = pathObj[0].definition;
}
return match;
};
const decorateWithNullable = (schema) => {
if (schema && schema.properties) {
Object.keys(schema.properties).forEach((prop) => {
if (schema.properties[prop]['x-nullable']) {
schema.properties[prop] = {
oneOf: [
schema.properties[prop],
{ type: 'null' },
],
};
}
});
} else if (schema && schema.items) {
schema.items = decorateWithNullable(schema.items);
}
return schema;
};
const resolveResponseModelSchema = (req, res) => {
const pathObj = matchUrlWithSchema(req.originalUrl);
let schema = null;
if (pathObj) {
const method = req.method.toLowerCase();
const responseSchemas = pathObj[method].responses;
const code = res.statusCode || 200;
if (responseSchemas[code]) {
schema = responseSchemas[code].schema;
}
}
if (options.allowNullable) {
schema = decorateWithNullable(schema);
}
return schema;
};
const resolveRequestModelSchema = (req) => {
const pathObj = matchUrlWithSchema(req.originalUrl);
let schema = null;
if (pathObj) {
const method = req.method.toLowerCase();
let requestSchemas = null;
if (pathObj[method]) {
requestSchemas = pathObj[method].parameters;
}
if (requestSchemas && requestSchemas.length > 0) {
schema = requestSchemas[0].schema;
}
}
if (options.allowNullable) {
schema = decorateWithNullable(schema);
}
return schema;
};
const sendData = (res, data, encoding) => {
// 'res.end' requires a Buffer or String so if it's not one, create a String
if (!(data instanceof Buffer) && !_.isString(data)) {
data = JSON.stringify(data);
}
res.end(data, encoding);
};
const validateResponse = (req, res, next) => {
const ajv = new Ajv({
allErrors: true,
formats: {
int32: valueValidator.isInt,
int64: valueValidator.isInt,
url: valueValidator.isURL,
},
});
let val;
const origEnd = res.end;
const writtenData = [];
const origWrite = res.write;
// eslint-disable-next-line
res.write = function (data) {
if (typeof data !== 'undefined') {
writtenData.push(data);
}
};
// eslint-disable-next-line
res.end = function (data, encoding) {
if (data) {
if (data instanceof Buffer) {
writtenData.push(data);
val = Buffer.concat(writtenData);
} else if (data instanceof String) {
writtenData.push(new Buffer(data));
val = Buffer.concat(writtenData);
} else {
val = data;
}
} else if (writtenData.length !== 0) {
val = Buffer.concat(writtenData);
}
if (data instanceof Buffer) {
debug(data.toString(encoding));
}
res.write = origWrite;
res.end = origEnd;
if (val instanceof Buffer) {
val = val.toString(encoding);
}
if (_.isString(val)) {
try {
val = JSON.parse(val);
} catch (err) {
err.failedValidation = true;
err.message = 'Value expected to be an array/object but is not';
throw err;
}
}
const responseSchema = resolveResponseModelSchema(req, res);
if (!responseSchema) {
debug('Response validation skipped: no matching response schema');
sendData(res, val, encoding);
} else {
const validator = ajv.compile(responseSchema);
const validation = validator(_.cloneDeep(val));
if (!validation) {
debug(` Response validation errors: \n${util.inspect(validator.errors)}`);
if (options.responseValidationFn) {
options.responseValidationFn(req, val, validator.errors);
sendData(res, val, encoding);
} else {
const err = {
message: `Response schema validation failed for ${req.method}${req.originalUrl}`,
};
next(err);
}
} else {
debug('Response validation success');
sendData(res, val, encoding);
}
}
};
next();
};
const validateRequest = (req, res, next) => {
const ajv = new Ajv({
allErrors: true,
formats: {
int32: valueValidator.isInt,
int64: valueValidator.isInt,
url: valueValidator.isURL,
},
});
const requestSchema = resolveRequestModelSchema(req);
if (!requestSchema) {
debug('Request validation skipped: no matching request schema');
if (options.validateResponse) {
validateResponse(req, res, next);
} else {
next();
}
} else {
const validator = ajv.compile(requestSchema);
const validation = validator(_.cloneDeep(req.body));
if (!validation) {
debug(` Request validation errors: \n${util.inspect(validator.errors)}`);
if (options.requestValidationFn) {
options.requestValidationFn(req, req.body, validator.errors);
next();
} else {
const err = {
message: `Request schema validation failed for ${req.method}${req.originalUrl}`,
};
res.status(400);
res.json(err);
}
} else {
debug('Request validation success');
if (options.validateResponse) {
validateResponse(req, res, next);
} else {
next();
}
}
}
};
const validate = (req, res, next) => {
debug(`Processing: ${req.method} ${req.originalUrl}`);
if (options.validateRequest) {
validateRequest(req, res, next);
} else if (options.validateResponse) {
validateResponse(req, res, next);
}
};
/**
*
* @param opts
* @param opts.schema {object} json swagger schema
* @param opts.validateResponse {boolean|true}
* @param opts.validateRequest {boolean|true}
* @param opts.allowNullable {boolean|true}
* @param opts.requestValidationFn {function}
* @param opts.responseValidationFn {function}
* @returns {function(*=, *=, *=)}
*/
const init = (opts = {}) => {
debug('Initializing swagger-express-validator middleware');
options = _.defaults(opts, {
validateRequest: true,
validateResponse: true,
allowNullable: true,
});
pathObjects = buildPathObjects(options.schema.paths);
return validate;
};
module.exports = init;