2020-02-13 11:49:03 +01:00
|
|
|
import * as express from 'express'
|
2020-05-29 09:13:22 +02:00
|
|
|
import { check, validationResult } from 'express-validator'
|
2020-02-13 11:49:03 +01:00
|
|
|
import { logger } from '../../helpers/logger'
|
|
|
|
|
|
|
|
function areValidationErrors (req: express.Request, res: express.Response) {
|
|
|
|
const errors = validationResult(req)
|
|
|
|
|
|
|
|
if (!errors.isEmpty()) {
|
2020-05-28 16:32:49 +02:00
|
|
|
logger.warn({ path: req.originalUrl, err: errors.mapped() }, 'Incorrect request parameters')
|
2020-02-13 11:49:03 +01:00
|
|
|
res.status(400).json({ errors: errors.mapped() })
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
function checkSort (sortableColumns: string[]) {
|
|
|
|
return [
|
2020-05-29 09:13:22 +02:00
|
|
|
check('sort').optional().isIn(sortableColumns).withMessage('Should have correct sortable column'),
|
2020-02-13 11:49:03 +01:00
|
|
|
|
|
|
|
(req: express.Request, res: express.Response, next: express.NextFunction) => {
|
|
|
|
if (areValidationErrors(req, res)) return
|
|
|
|
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
function createSortableColumns (sortableColumns: string[]) {
|
|
|
|
const sortableColumnDesc = sortableColumns.map(sortableColumn => '-' + sortableColumn)
|
|
|
|
|
|
|
|
return sortableColumns.concat(sortableColumnDesc)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
|
|
|
areValidationErrors,
|
|
|
|
checkSort,
|
|
|
|
createSortableColumns
|
|
|
|
}
|