-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathswagger_validator.js
More file actions
59 lines (54 loc) · 1.83 KB
/
swagger_validator.js
File metadata and controls
59 lines (54 loc) · 1.83 KB
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
const get = require('mout/object/get');
const {isFunction, isArray, isEmpty} = require('mout/lang');
const reject = require('mout/array/reject');
const errors = require('./errors');
/**
* Wrapper of default swagger_validator
* @see swagger-node-runner/fittings/swagger_validator.js
*/
module.exports = (fittingDef, pipes) => {
const fn = get(pipes, 'config.swaggerNodeRunner.swaggerTools.swaggerValidator');
let middleware;
if (isFunction(fn)) {
// swagger-express-mw@0.1.0
const validatorConfig = {
validateResponse: !!fittingDef.validateResponse
};
middleware = fn(validatorConfig);
} else {
// swagger-express-mw@0.7.0
middleware = (req, res, next) => {
if (!req.swagger.operation) {
return next();
}
const validateResult = req.swagger.operation.validateRequest(req);
if (!validateResult.errors.length) {
return next();
}
next({
failedValidation: true,
results: validateResult.errors,
});
};
}
return (context, next) => {
middleware(context.request, context.response, err => {
if (!err || !err.failedValidation) {
// validationエラー以外はスルー
return next(err);
}
const results = isArray(err.results) ? err.results : [err.results];
const newErrors = reject(results, result => {
return isEmpty(reject(result.errors, err => {
return err.code === 'ENUM_MISMATCH' || // 動的生成部分のvalidateができないので無視する
err.message.match(/^Expected type [\w.]+ but found type null$/); // type: null 以外のフィールドでもnull値を許容する
}));
});
if (newErrors.length) {
return next(errors.frontend.ValidationFailure(newErrors));
}
context.response.statusCode = 200;
next();
});
};
};