summaryrefslogtreecommitdiff
path: root/goodgame/src/utils/common.js
blob: 7f4065874096db51214e211ad31e10e2c70a3773 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const { validationResult } = require('express-validator/check');

const formatResponse = (status, data) => ({ ok: status, response: data });

const validatorMiddleware = (req, res, next) => {
  const errorFormatter = ({ msg, param }) => `${param}: ${msg}`;
  const errors = validationResult(req).formatWith(errorFormatter);
  if (!errors.isEmpty()) {
    return res.status(422).json(formatResponse(false, errors.array()));
  }
  return next();
};

const getRandomArbitrary = (min, max) => {
  return Math.random() * (max - min) + min;
};

const shuffle = array => {
  let j;
  let x;
  for (let i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1));
    x = array[i];
    array[i] = array[j];
    array[j] = x;
  }
  return array;
};

module.exports = {
  formatResponse,
  validatorMiddleware,
  getRandomArbitrary,
  shuffle,
};