const Books = require("Books.js")
async getBooks(req, res, next) {
let query;
let reqQuery = { ...req.query };
const removeFields = ["select", "sort"];
removeFields.forEach(param => delete reqQuery[param]);
let queryStr = JSON.stringify(reqQuery);
queryStr = queryStr.replace(
/(gt|gte|lt|lte|in)/g,
match => `$${match}`
);
query = Books.findQuery(JSON.parse(queryStr));
if (req.query.select) {
const fields = req.query.select.split(",").join(" ");
query = query.select(fields);
}
if (req.query.sort) {
const sortBy = req.query.sort.split(",").join(" ");
query = query.sort(sortBy);
} else {
query = query.sort("-createdAt");
}
const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 10;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const total = await Books.countDocuments();
query = query.skip(startIndex).limit(limit);
let books = await query;
const pagination = {};
if (endIndex < total) {
pagination.next = {
page: page + 1,
limit,
};
}
if (startIndex > 0) {
pagination.prev = {
page: page - 1,
limit,
};
}
res.status(200).json({
success: true,
count: books.length,
pagination,
data: books,
});
}