import { checkSchema } from 'express-validator'; import User from '../models/users'; import Role from '../models/roles'; import { Op } from 'sequelize'; const validateUser = checkSchema({ name: { notEmpty: { errorMessage: 'Name is required', }, }, email: { notEmpty: { errorMessage: 'Email is required', }, isEmail: { errorMessage: 'Invalid email address', }, custom: { options: async (value) => { const ifUserExists = await User.findOne({ where: { email: value } }); if (ifUserExists) { return Promise.reject('User already exists'); } }, }, }, password: { notEmpty: { errorMessage: 'Password is required', }, isLength: { options: { min: 8 }, errorMessage: 'Password must be at least 8 characters long', }, }, status: { notEmpty: { errorMessage: 'Status is required', }, }, role_id: { notEmpty: { errorMessage: 'Role ID is required', }, custom: { options: async (value) => { const role = await Role.findByPk(value); if (!role) { return Promise.reject('Role ID is invalid'); } }, }, }, }); const validateUserUpdate = checkSchema({ email: { optional: true, isEmail: { errorMessage: 'Invalid email address', }, custom: { options: async (value, { req }: { req: any}) => { const id = req.params.id; const ifUserExists = await User.findOne({ where: { email: value, id: { [Op.ne]: id } } }); if (ifUserExists) { return Promise.reject('User already exists'); } }, }, }, role_id: { optional: true, custom: { options: async (value) => { const role = await Role.findByPk(value); if (!role) { return Promise.reject('Role ID is invalid'); } }, }, }, password: { optional: true, isLength: { options: { min: 8 }, errorMessage: 'Password must be at least 8 characters long', }, }, }); export { validateUser, validateUserUpdate };