-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.js
335 lines (301 loc) · 9 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
const _ = require('lodash');
const debug = require('debug')('swagger-express-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 = {};
let ajvRequestOptions;
let ajvResponseOptions;
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 removeBasePath = (basePath, url) => (url.indexOf(basePath) === 0
? url.replace(basePath, '')
: url);
const normalizeUrl = (url) => {
if (options.schema.basePath) {
return removeBasePath(options.schema.basePath, url);
}
return url;
};
const matchUrlWithSchema = (reqUrl) => {
const url = normalizeUrl(parseUrl(reqUrl).pathname);
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 decorateWithDefinitions = (schema) => {
schema.definitions = _.assign({}, options.schema.definitions || {}, schema.definitions || {});
return schema;
};
const resolveResponseModelSchema = (req, res) => {
const pathObj = matchUrlWithSchema(req.originalUrl);
let schema = null;
if (pathObj) {
const method = req.method.toLowerCase();
if (pathObj[method]) {
const responseSchemas = pathObj[method].responses;
const code = res.statusCode || 200;
if (responseSchemas[code]) {
({ schema } = responseSchemas[code]);
}
}
}
if (options.allowNullable) {
schema = decorateWithNullable(schema);
}
if (options.schema.definitions && schema) {
schema = decorateWithDefinitions(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) {
const bodyParam = _.find(requestSchemas, { in: 'body' });
schema = bodyParam && bodyParam.schema;
}
}
if (options.allowNullable) {
schema = decorateWithNullable(schema);
}
if (options.schema.definitions && schema) {
schema = decorateWithDefinitions(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(Object.assign(
{},
{
allErrors: true,
formats: {
int32: valueValidator.isInt,
int64: valueValidator.isInt,
url: valueValidator.isURL,
},
},
ajvResponseOptions
));
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) {
res.write = origWrite;
res.end = origEnd;
const responseSchema = resolveResponseModelSchema(req, res);
if (!responseSchema) {
debug('Response validation skipped: no matching response schema');
sendData(res, data, encoding);
} else {
let val;
if (data) {
if (data instanceof Buffer) {
writtenData.push(data);
val = Buffer.concat(writtenData);
} else if (data instanceof String) {
writtenData.push(Buffer.from(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));
}
if (val instanceof Buffer) {
val = val.toString(encoding);
}
if (_.isString(val)) {
try {
val = JSON.parse(val);
} catch (err) {
if (!options.preserveResponseContentType) {
res.set('Content-Type', ''); // Reset content-type since it is no longer valid
}
err.failedValidation = true;
err.message = 'Value expected to be an array/object but is not';
if (options.responseValidationFn) {
options.responseValidationFn(req, data, [err]);
sendData(res, data, encoding);
return;
}
const resultError = {
message: `Response schema validation failed for ${req.method}${req.originalUrl}`,
};
if (options.returnResponseErrors) {
err.errors = [{ message: 'Invalid response format' }];
}
next(resultError);
return;
}
}
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}`,
};
if (options.returnResponseErrors) {
err.errors = validator.errors;
}
next(err);
}
} else {
debug('Response validation success');
sendData(res, val, encoding);
}
}
};
next();
};
const validateRequest = (req, res, next) => {
const ajv = new Ajv(Object.assign(
{},
{
allErrors: true,
formats: {
int32: valueValidator.isInt,
int64: valueValidator.isInt,
url: valueValidator.isURL,
},
}, ajvRequestOptions
));
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}`,
};
if (options.returnRequestErrors) {
err.errors = validator.errors;
}
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 (pathObjects.length === 0) {
next();
} else if (options.validateRequest) {
validateRequest(req, res, next);
} else if (options.validateResponse) {
validateResponse(req, res, next);
} else {
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}
* @param [opts.ajvRequestOptions] {object}
* @param [opts.ajvResponseOptions] {object}
* @returns {function(*=, *=, *=)}
*/
const init = (opts = {}) => {
debug('Initializing swagger-express-validator middleware');
options = _.defaults({}, opts, {
preserveResponseContentType: true,
returnResponseErrors: false,
returnRequestErrors: false,
validateRequest: true,
validateResponse: true,
allowNullable: true,
ajvRequestOptions: {},
ajvResponseOptions: {},
});
if (options.schema) {
pathObjects = buildPathObjects(options.schema.paths);
} else {
debug('Please provide schema option to properly initialize middleware');
pathObjects = [];
}
({ ajvRequestOptions, ajvResponseOptions } = opts);
return validate;
};
module.exports = init;