-
Notifications
You must be signed in to change notification settings - Fork 2
/
booksValidate.js
72 lines (70 loc) · 2.07 KB
/
booksValidate.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
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
const validator = require('validator');
const BOOK = require('../models/book');
const USER = require('../models/user');
const isDataMissed = require('../helpers/checkRequestData');
class BooksValidator {
constructor() {
this.validateCreateBook = async (req, res, next) => {
// CHECK FOR NEEDED DATA
if (isDataMissed(req.body, 'title')) {
return res.status(400).json({
status: 'error',
msg: 'please enter the required fields to create book (title)',
});
}
// CHECK IF BOOK WITH THE SAME TITLE IS EXIST
const { title } = req.body;
if (await BOOK.findOne({ title })) {
return res.status(400).json({
status: 'error',
msg: 'a book with the same title is already exist.',
});
}
// CONTINUE
next();
};
// VALIDATE ADD BOOK TO USER WISHLIST
this.validateAddToWishList = async (req, res, next) => {
// GET USER ID AND BOOK ID FROM REQUEST BODY
const { bookId } = req.body;
if (!bookId) {
return res.status(400).json({
status: 'error',
msg: 'please enter book id.',
});
}
try {
const book = await BOOK.findById(bookId);
if (!book) {
return res.status(400).json({
status: 'error',
msg: 'no book found with this id.',
});
}
req.bookID = book._id;
req.bookTitle = book.title;
req.bookPrice = book.price;
req.bookQuantity = book.quantity;
next();
} catch (error) {
return res.status(400).json({
status: 'error',
msg: 'no book found with this id.',
});
}
};
// VALIDATE REMOVE ITEM FROM USER CART
this.validateRemoveFromCart = async (req, res, next) => {
const { itemId } = req.body;
if (!itemId) {
return res.status(400).json({
status: 'error',
msg: 'please enter the cart item id you want to delete.',
});
}
req.itemId = itemId;
next();
};
}
}
module.exports = new BooksValidator();