X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fmiddlewares%2Fvalidators%2Futils.ts;h=43e5652fa2c2764706da943d5eb122b78ac46230;hb=c6c0fa6cd8fe8f752463d8982c3dbcd448739c4e;hp=710e65529684d5633a03fb630da7d7ab00328818;hpb=65fcc3119c334b75dd13bcfdebf186afdc580a8f;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/middlewares/validators/utils.ts b/server/middlewares/validators/utils.ts index 710e65529..43e5652fa 100644 --- a/server/middlewares/validators/utils.ts +++ b/server/middlewares/validators/utils.ts @@ -1,21 +1,44 @@ -import { inspect } from 'util' +import * as express from 'express' +import { query, validationResult } from 'express-validator' +import { logger } from '../../helpers/logger' -import { logger } from '../../helpers' +function areValidationErrors (req: express.Request, res: express.Response) { + const errors = validationResult(req) -function checkErrors (req, res, next, statusCode?) { - if (statusCode === undefined) statusCode = 400 - const errors = req.validationErrors() + if (!errors.isEmpty()) { + logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors.mapped() }) + res.status(400).json({ errors: errors.mapped() }) - if (errors) { - logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors }) - return res.status(statusCode).send('There have been validation errors: ' + inspect(errors)) + return true } - return next() + return false +} + +function checkSort (sortableColumns: string[]) { + return [ + query('sort').optional().isIn(sortableColumns).withMessage('Should have correct sortable column'), + + (req: express.Request, res: express.Response, next: express.NextFunction) => { + logger.debug('Checking sort parameters', { parameters: req.query }) + + if (areValidationErrors(req, res)) return + + return next() + } + ] +} + +function createSortableColumns (sortableColumns: string[]) { + const sortableColumnDesc = sortableColumns.map(sortableColumn => '-' + sortableColumn) + + return sortableColumns.concat(sortableColumnDesc) } // --------------------------------------------------------------------------- export { - checkErrors + areValidationErrors, + checkSort, + createSortableColumns }