Skip to content

Instantly share code, notes, and snippets.

@royhowie
Last active August 29, 2015 14:24
Show Gist options
  • Save royhowie/b8ccf9744e03f3d23917 to your computer and use it in GitHub Desktop.
Save royhowie/b8ccf9744e03f3d23917 to your computer and use it in GitHub Desktop.
pagination in es6 vs es7
function paginate (title, baseQuery, baseUrl, errorRedirect, methods) {
if (!baseQuery.count || !baseQuery.paginateSort) {
throw new Error('baseQuery is missing a count or paginateSort method! - paginate.js')
} else if (!methods.length) {
throw new Error('methods must be an array of methods to apply to each document! - paginate.js')
}
return (req, res) => {
let documentsPerPage = Math.min(parseInt(req.query.perpage) || 15, 100)
let page = Math.max(parseInt(req.query.page), 0)
baseQuery.count().then((documentCount) => {
if (page * documentsPerPage > documentCount) {
req.flash('message', `Page ${ page } does not exist. Redirecting to the first page.`)
res.redirect(baseUrl)
} else {
return baseQuery.paginateSort(page, documentsPerPage).then((documents) => {
res.render('admin/paginate.jade', {
baseUrl,
count: documentCount,
documents,
documentsPerPage,
message: req.flash('message'),
page,
title,
user: req.user,
})
})
}
}).catch((err) => {
req.flash('message', err.message || err)
res.redirect(errorRedirect)
})
}
}
function paginate (title, baseQuery, baseUrl, errorRedirect, methods) {
if (!baseQuery.count || !baseQuery.paginateSort) {
throw new Error('baseQuery is missing a count or paginateSort method! - paginate.js')
} else if (!methods.length) {
throw new Error('methods must be an array of methods to apply to each document! - paginate.js')
}
return (req, res) => {
let documentsPerPage = Math.min(parseInt(req.query.perpage) || 15, 100)
let page = Math.max(parseInt(req.query.page), 0)
try {
let documentCount = await baseQuery.count()
if (page * documentsPerPage > documentCount) {
req.flash('message', `Page ${ page } does not exist. Redirecting to the first page.`)
return res.redirect(baseUrl)
}
let documents = await baseQuery.paginateSort(page, documentsPerPage)
return res.render('admin/paginate.jade', {
baseUrl,
count: documentCount,
documents,
documentsPerPage,
message: req.flash('message'),
page,
title,
user: req.user,
})
} catch (err) {
req.flash('message', err.message || err)
res.redirect(errorRedirect)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment