From 5c328e6610f451d114c30d3a3b4e5d41b3b4b612 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 13 Mar 2018 11:28:37 +0100 Subject: Move sort middleware utils in utils file --- server/middlewares/validators/utils.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) (limited to 'server/middlewares/validators/utils.ts') diff --git a/server/middlewares/validators/utils.ts b/server/middlewares/validators/utils.ts index 55b140103..8f77c9fbd 100644 --- a/server/middlewares/validators/utils.ts +++ b/server/middlewares/validators/utils.ts @@ -1,5 +1,5 @@ import * as express from 'express' -import { validationResult } from 'express-validator/check' +import { query, validationResult } from 'express-validator/check' import { logger } from '../../helpers/logger' function areValidationErrors (req: express.Request, res: express.Response) { @@ -15,8 +15,30 @@ function areValidationErrors (req: express.Request, res: express.Response) { 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 { - areValidationErrors + areValidationErrors, + checkSort, + createSortableColumns } -- cgit v1.2.3