]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import { query, validationResult } from 'express-validator' | |
3 | import { logger } from '../../helpers/logger' | |
4 | ||
5 | function areValidationErrors (req: express.Request, res: express.Response) { | |
6 | const errors = validationResult(req) | |
7 | ||
8 | if (!errors.isEmpty()) { | |
9 | logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors.mapped() }) | |
10 | res.fail({ | |
11 | message: 'Incorrect request parameters: ' + Object.keys(errors.mapped()).join(', '), | |
12 | instance: req.originalUrl, | |
13 | data: { | |
14 | 'invalid-params': errors.mapped() | |
15 | } | |
16 | }) | |
17 | ||
18 | return true | |
19 | } | |
20 | ||
21 | return false | |
22 | } | |
23 | ||
24 | function checkSort (sortableColumns: string[], tags: string[] = []) { | |
25 | return [ | |
26 | query('sort').optional().isIn(sortableColumns).withMessage('Should have correct sortable column'), | |
27 | ||
28 | (req: express.Request, res: express.Response, next: express.NextFunction) => { | |
29 | logger.debug('Checking sort parameters', { parameters: req.query, tags }) | |
30 | ||
31 | if (areValidationErrors(req, res)) return | |
32 | ||
33 | return next() | |
34 | } | |
35 | ] | |
36 | } | |
37 | ||
38 | function createSortableColumns (sortableColumns: string[]) { | |
39 | const sortableColumnDesc = sortableColumns.map(sortableColumn => '-' + sortableColumn) | |
40 | ||
41 | return sortableColumns.concat(sortableColumnDesc) | |
42 | } | |
43 | ||
44 | // --------------------------------------------------------------------------- | |
45 | ||
46 | export { | |
47 | areValidationErrors, | |
48 | checkSort, | |
49 | createSortableColumns | |
50 | } |