-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
42 lines (34 loc) · 1.08 KB
/
utils.js
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
const { validationResult, check } = require('express-validator');
const { User } = require('./db/models/user');
const asyncHandler = (handler) => (req, res, next) => handler(req, res, next).catch(next);
const validateEmailAndPassword = [
check("email")
.exists({ checkFalsy: true })
.isEmail()
.withMessage("Please provide a valid email."),
check("password")
.exists({ checkFalsy: true })
.withMessage("Please provide a password.")
];
const handleValidationErrors = (req, res, next) => {
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
const errors = validationErrors.array().map((error) => error.msg);
const err = Error("Bad request.");
err.status = 400;
err.title = "Bad request.";
err.errors = errors;
res.status(400).json({ err });
}
next();
};
const emailNotUnique = async (email) => {
const emails = await User.findAll().map((user) => user = user.email);
return emails.includes(email);
};
module.exports = {
asyncHandler,
handleValidationErrors,
emailNotUnique,
validateEmailAndPassword
}