added validators for data in route and authorization
This commit is contained in:
parent
7a915e1931
commit
fa7971bb2b
|
|
@ -0,0 +1,11 @@
|
|||
import { check } from 'express-validator'
|
||||
|
||||
const varChar = (field, { max = 255 } = {}) => check(field).isString().trim().isLength({ min: 1, max }).withMessage(`|${field}| must be a string with a length between 1 and ${max}`)
|
||||
const integer = field => check(field).isInt({min: Number.MIN_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER}).withMessage(`|${field}| must be an integer`)
|
||||
const uuid = field => check(field).isUUID('all').withMessage(`|${field}| must be a valid UUID`)
|
||||
|
||||
export {
|
||||
integer,
|
||||
uuid,
|
||||
varChar,
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { validationResult } from 'express-validator'
|
||||
import { errorHandler } from '../../utils/errors.js'
|
||||
|
||||
const payloadExpressValidator = (req, res, next, config) => {
|
||||
const errors = validationResult(req)
|
||||
if (!errors.isEmpty()) {
|
||||
const badRequest = errors.array().find(val => undefined === val.value)
|
||||
|
||||
if (badRequest) {
|
||||
const errorMessage = errorHandler({ errors: errors.array(), code: 'BAD_REQUEST' }, config.environment)
|
||||
return res.status(errorMessage.code).json(errorMessage)
|
||||
}
|
||||
|
||||
const error = errorHandler({ errors: errors.array(), code: 'UNPROCESSABLE_ENTITY' }, config.environment)
|
||||
return res.status(error.code).json(error)
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
export { payloadExpressValidator }
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
const filterByStock = (arr, min = 0, max = Number.MAX_VALUE) => {
|
||||
return arr
|
||||
.filter((item) => item.stock >= min && item.stock <= max)
|
||||
}
|
||||
|
||||
export {filterByStock}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import { sendResponseAccessDenied } from "../utils/responses"
|
||||
|
||||
const validateKeyValuePairFromToken = ({ key, values, singleValidation }) => (req, res, next, config) => {
|
||||
const fieldValue = ((req.auth || {}).user || {})[key]
|
||||
if (fieldValue && values.includes(fieldValue)) {
|
||||
return singleValidation
|
||||
? next({ error: false })
|
||||
: true
|
||||
}
|
||||
|
||||
return singleValidation
|
||||
? sendResponseAccessDenied({ res, config })
|
||||
: (req, res, env, next) => next({ error: true })
|
||||
}
|
||||
|
||||
export { validateKeyValuePairFromToken }
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
const noResults = (data) => {
|
||||
return data && data.length < 1
|
||||
}
|
||||
|
||||
export { noResults }
|
||||
Loading…
Reference in New Issue