|
1 | | -var _ = require('lodash') |
2 | | -var self = { |
3 | | - validation: require('./validation'), |
4 | | - error: require('./error'), |
5 | | - model: require('./model'), |
6 | | - when: require('./conditions'), |
7 | | -} |
| 1 | +const _ = require('lodash') |
| 2 | +const validation = require('./validation') |
| 3 | +const error = require('./error') |
| 4 | +const model = require('./model') |
| 5 | +const when = require('./conditions') |
8 | 6 |
|
9 | | -module.exports.validation = self.validation |
10 | | -module.exports.error = self.error |
11 | | -module.exports.when = self.when |
12 | | -module.exports.validatorModels = self.model.validatorModels |
| 7 | +module.exports.validation = validation |
| 8 | +module.exports.error = error |
| 9 | +module.exports.when = when |
| 10 | +module.exports.validatorModels = model.validatorModels |
| 11 | +module.exports.validationPlugin = validationPlugin |
13 | 12 |
|
14 | | -var defaultOptions = { |
| 13 | +const DEFAULT_OPTIONS = { |
15 | 14 | errorsAsArray: true, |
16 | 15 | errorHandler: false, |
17 | 16 | forbidUndefinedVariables: false, |
18 | 17 | validatorModels: {}, |
19 | 18 | } |
20 | 19 |
|
21 | | -module.exports.validationPlugin = function (options) { |
22 | | - options = _.extend({}, defaultOptions, options) |
| 20 | +function validationPlugin(options) { |
| 21 | + // Massage options |
| 22 | + options = { ...DEFAULT_OPTIONS, ...options } |
23 | 23 | if (_.isArray(options.validatorModels)) { |
24 | | - // Combine list of validatorModels |
25 | | - var validatorModels = _.toArray(options.validatorModels) |
26 | | - validatorModels.unshift({}) |
27 | | - options.validatorModels = _.extend.apply(null, validatorModels) |
| 24 | + options.validatorModels = options.validatorModels.reduce((acc, models) => ({ |
| 25 | + ...acc, |
| 26 | + ...models, |
| 27 | + })) |
28 | 28 | } |
29 | | - return function (req, res, next) { |
30 | | - var validationModel = req.route ? req.route.validation : undefined |
| 29 | + |
| 30 | + // Produce middleware |
| 31 | + return function restifyFreshValidationMW(req, res, next) { |
| 32 | + const spec = (req.route && req.route.spec) || req.route |
| 33 | + const validationModel = spec && spec.validation |
31 | 34 |
|
32 | 35 | if (validationModel) { |
33 | | - // validate |
34 | | - var errors = self.validation.process(validationModel, req, options) |
| 36 | + const errors = validation.process(validationModel, req, options) |
35 | 37 |
|
36 | 38 | if ( |
37 | 39 | (errors && options.errorsAsArray && errors.length > 0) || |
38 | | - (!options.errorsAsArray && _.keys(errors).length > 0) |
| 40 | + (!options.errorsAsArray && Object.keys(errors).length > 0) |
39 | 41 | ) { |
40 | | - return self.error.handle(errors, req, res, options, next) |
| 42 | + return error.handle(errors, req, res, options, next) |
41 | 43 | } |
42 | 44 | } |
43 | 45 |
|
|
0 commit comments