|
|
|
const {body, validationResult} = require('express-validator')
|
|
|
|
const db = require('../../db')
|
|
|
|
|
|
|
|
const validators = module.exports = {}
|
|
|
|
|
|
|
|
validators.validPassword = field => body(field).isString().isLength({min: 8, max: 100}).withMessage('Password must be at least 8 characters')
|
|
|
|
|
|
|
|
validators.bothPasswordsMatch = body('password').custom((pass, {req})=>{
|
|
|
|
if(pass !== req.body.password2)
|
|
|
|
throw new Error('Passwords do not match')
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
validators.validEmail = field => body(field).isString().isEmail()
|
|
|
|
.withMessage('Email invalid')
|
|
|
|
|
|
|
|
validators.unusedEmail = field => validators.validEmail(field)
|
|
|
|
.custom(async email=>{
|
|
|
|
const user = await db.user.findByEmail(email)
|
|
|
|
if(user) throw new Error('Email already in use')
|
|
|
|
})
|
|
|
|
|
|
|
|
validators.validUrlSlug = field => body(field).isString().isLength({min: 3, max: 20}).matches(/^[-a-z0-9_]*$/i)
|
|
|
|
.withMessage('Slug can be between 3-20 characters long, and can include letters, numbers, dash or underscore')
|
|
|
|
|
|
|
|
validators.requiredString = field => body(field).isString()
|
|
|
|
.withMessage('Required')
|
|
|
|
|
|
|
|
validators.positiveInteger = field => body(field).isInt().custom(value => value > 0)
|
|
|
|
.withMessage('Must be a positive integer')
|
|
|
|
|
|
|
|
validators.publishedBool = body('published').isBoolean()
|
|
|
|
|
|
|
|
validators.isUUID = field => body(field).isString().isUUID()
|
|
|
|
|
|
|
|
validators.address = [
|
|
|
|
body('street1').isString().isLength({min: 1}).withMessage('Street address is required'),
|
|
|
|
body('city').isString().isLength({min: 1}).withMessage('City is required'),
|
|
|
|
body('state').isString().isLength({min: 1}).withMessage('State is required'),
|
|
|
|
body('zip').isString().isLength({min: 1}).withMessage('Postal code is required')
|
|
|
|
]
|
|
|
|
|
|
|
|
validators.handleApiError = (req, res, next) => {
|
|
|
|
const errors = validationResult(req)
|
|
|
|
|
|
|
|
if(errors.isEmpty())
|
|
|
|
return next()
|
|
|
|
|
|
|
|
res.status(422).json({errors: errors.array()})
|
|
|
|
}
|