1 | const allLocations = ['params', 'query', 'body', 'headers', 'cookies'];
|
2 |
|
3 | function validateSchema(schema, req, loc, chainCreator) {
|
4 | Object.keys(schema)
|
5 | .map(param => ({ name, loc, cfg: schema[param] }))
|
6 | .map(locationMapper)
|
7 | .filter(locationFilter)
|
8 | .map(param => Object.assign(param, { chain: chainCreator(param) }))
|
9 | .forEach(setupChain);
|
10 | }
|
11 |
|
12 | function setupChain(param) {
|
13 | Object.keys(param.cfg)
|
14 | .map(name => ({ name, param, cfg: param.cfg[name] }))
|
15 | .filter(configMethodFilter)
|
16 | .filter(inexistentMethodFilter)
|
17 | .forEach(setValidator);
|
18 | }
|
19 |
|
20 | function setValidator({ name, cfg, param: { chain } }) {
|
21 | const options = [].concat(cfg.options);
|
22 | chain[name](...options);
|
23 | name !== 'optional' && chain.withMessage(cfg.errorMessage);
|
24 | }
|
25 |
|
26 | function configMethodFilter({ name, cfg }) {
|
27 | return ['in', 'errorMessage'].includes(name) || !cfg;
|
28 | }
|
29 |
|
30 | function inexistentMethodFilter({ name, param }) {
|
31 | if (typeof param.chain[name] !== 'function') {
|
32 | console.warn(`express-validator: a validator with name ${name} does not exist`);
|
33 | return false;
|
34 | }
|
35 |
|
36 | return true;
|
37 | }
|
38 |
|
39 | function locationMapper(param) {
|
40 | const loc = param.cfg.in || (param.loc === 'any' ? allLocations : param.loc);
|
41 | return Object.assign(param, { loc });
|
42 | }
|
43 |
|
44 | function locationFilter(param) {
|
45 | return allLocations.includes(param.loc);
|
46 | } |
\ | No newline at end of file |