utils.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import * as express from 'express'
  2. import { query, validationResult } from 'express-validator/check'
  3. import { logger } from '../../helpers/logger'
  4. function areValidationErrors (req: express.Request, res: express.Response) {
  5. const errors = validationResult(req)
  6. if (!errors.isEmpty()) {
  7. logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors.mapped() })
  8. res.status(400).json({ errors: errors.mapped() })
  9. return true
  10. }
  11. return false
  12. }
  13. function checkSort (sortableColumns: string[]) {
  14. return [
  15. query('sort').optional().isIn(sortableColumns).withMessage('Should have correct sortable column'),
  16. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  17. logger.debug('Checking sort parameters', { parameters: req.query })
  18. if (areValidationErrors(req, res)) return
  19. return next()
  20. }
  21. ]
  22. }
  23. function createSortableColumns (sortableColumns: string[]) {
  24. const sortableColumnDesc = sortableColumns.map(sortableColumn => '-' + sortableColumn)
  25. return sortableColumns.concat(sortableColumnDesc)
  26. }
  27. // ---------------------------------------------------------------------------
  28. export {
  29. areValidationErrors,
  30. checkSort,
  31. createSortableColumns
  32. }