Spaces:
Runtime error
Runtime error
File size: 2,186 Bytes
6a978cd 01458b3 ed11216 01458b3 32381c2 01458b3 32381c2 ed11216 32381c2 ed11216 32381c2 6a978cd 32381c2 |
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
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 }; |