-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.js
60 lines (52 loc) · 1.43 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const fs = require('fs');
const Product = require('./models/product');
const ITEMS_PER_PAGE = 2;
const fetchAllProducts = (file, title, path, req, res, next, condition = {}) => {
let page = +req.query.page || 1;
let totalProducts;
Product.find(condition).countDocuments()
.then(productsCount => {
totalProducts = productsCount;
return Product.find(condition)
.skip((page - 1) * ITEMS_PER_PAGE)
.limit(ITEMS_PER_PAGE)
})
.then((products) => res.render(file, {
products,
title,
path,
currentPage: page,
hasNextPage: ITEMS_PER_PAGE * page < totalProducts,
hasPreviousPage: page > 1,
nextPage: page + 1,
previousPage: page - 1,
lastPage: Math.ceil(totalProducts / ITEMS_PER_PAGE)
}))
.catch(err => forwardError(err, next));
};
const getErrorMessage = (req) => {
let errorMessage = req.flash('error');
if (errorMessage.length > 0) {
errorMessage = errorMessage[0];
} else {
errorMessage = null;
}
return errorMessage;
};
const forwardError = (err, next) => {
console.log(err);
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
}
const deleteFile = (filePath) => {
fs.unlink(filePath, (err) => {
if (err) {
throw err;
}
})
}
exports.fetchAllProducts = fetchAllProducts;
exports.getErrorMessage = getErrorMessage;
exports.forwardError = forwardError;
exports.deleteFile = deleteFile;