Skip to content

Instantly share code, notes, and snippets.

@nax3t
Created September 18, 2018 22:43
Show Gist options
  • Save nax3t/43c80e4ac27929f7379ec97ee2110c2b to your computer and use it in GitHub Desktop.
Save nax3t/43c80e4ac27929f7379ec97ee2110c2b to your computer and use it in GitHub Desktop.
posts index method (get all posts or filter)
index: async (req, res, next) => {
let posts, filters, query;
// define escapeRegex function for search feature
const escapeRegex = (text) => {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
// check if filters exist
if (req.query.post) filters = Object.values(req.query.post).join('') ? true : false;
// check if request has filter(s)
if (filters) {
let { search, condition, category, price, location, longitude, latitude } = req.query.post;
// build $and query array
query = [];
if (search) {
search = new RegExp(escapeRegex(search), 'gi');
query.push({ $or: [
{ title: search },
{ description: search },
{ location: search },
{ condition: search },
{ category: search }
]});
}
if (condition) {
if (Array.isArray(condition)) condition = '(' + condition.join('?|') + '?)';
query.push({ condition: new RegExp(condition, 'gi') });
}
if (category) {
res.locals.category = category; // make category available in view
if (Array.isArray(category)) category = '(' + category.join('?|') + '?)';
query.push({ category: new RegExp(category, 'gi') });
}
if (price) {
if (price.min) query.push({ price: { $gte: price.min } });
if (price.max) query.push({ price: { $lte: price.max } });
}
if (longitude && latitude) {
// get the max distance or set it to 25 mi
let maxDistance = req.query.post.distance || 25;
// we need to convert the distance to degrees, one degree is approximately 69 miles
maxDistance /= 69;
// get coordinates [ <longitude> , <latitude> ]
let coords = [
longitude,
latitude
];
query.push({
coordinates: {
$near: coords,
$maxDistance: maxDistance
}
});
}
query = query.length ? { $and: query } : {};
}
posts = await Post.paginate(query, { page: req.query.page, limit: req.query.limit, sort: { '_id': -1 } });
if(req.xhr) {
// send back json with status of 200 (OK)
res.status(200).json({
posts: posts.docs,
pageNumber: posts.page,
has_next: paginate.hasNextPages(req)(posts.pages),
has_prev: req.query.page > 1,
pages: paginate.getArrayPages(req)(3, posts.pages, req.query.page),
nextUrl: paginate.href(req)(),
prevUrl: paginate.href(req)(true)
});
} else {
// render index view
res.render('posts/index', {
title: 'Posts Index',
page: 'posts',
posts: posts.docs,
pageNumber: posts.page,
pageCount: posts.pages,
itemCount: posts.limit,
pages: paginate.getArrayPages(req)(3, posts.pages, req.query.page),
error: posts.total ? '' : 'No results available for that search'
});
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment