diff options
Diffstat (limited to 'goodgame/src/utils/common.js')
-rw-r--r-- | goodgame/src/utils/common.js | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/goodgame/src/utils/common.js b/goodgame/src/utils/common.js new file mode 100644 index 0000000..7f40658 --- /dev/null +++ b/goodgame/src/utils/common.js @@ -0,0 +1,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, +}; |