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