• Stars
    star
    419
  • Rank 103,397 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Paginate middleware

express-paginate

NPM Version NPM Downloads Build Status Test Coverage MIT License Slack

Node.js pagination middleware and view helpers.

Looking for a Koa version? Try using https://github.com/koajs/ctx-paginate, which is forked directly from this package!

v0.2.0+: As of v0.2.0, we now allow you to pass ?limit=0 to get infinite (all) results. This may impose security or performance issues for your application, so we suggest you to write a quick middleware fix such as the one below, or use rate limiting middleware to prevent abuse.

app.all(function(req, res, next) {
  // set default or minimum is 10 (as it was prior to v0.2.0)
  if (req.query.limit <= 10) req.query.limit = 10;
  next();
});

Install

npm install -S express-paginate

API

const paginate = require('express-paginate');

paginate

This creates a new instance of express-paginate.

paginate.middleware(limit, maxLimit)

This middleware validates and supplies default values to req.skip (an alias of req.offset, which can be used to skip or offset a number of records for pagination, e.g. with Mongoose you would do Model.find().skip(req.skip)), req.query.limit, req.query.page, res.locals.paginate, res.locals.hasPreviousPages, and res.locals.hasNextPages.

Arguments

  • limit a Number to limit results returned per page (defaults to 10)
  • maxLimit a Number to restrict the number of results returned to per page (defaults to 50) – through this, users will not be able to override this limit (e.g. they can't pass ?limit=10000 and crash your server)

paginate.href(req)

When you use the paginate middleware, it injects a view helper function called paginate.href as res.locals.paginate, which you can use in your views for paginated hyperlinks (e.g. as the href in <a>Prev</a> or <a>Next</a>).

By default, the view helper paginate.href is already executed with the inherited req variable, therefore it becomes a function capable of returning a String when executed.

When executed with req, it will return a function with two optional arguments, prev (Boolean) and params (String).

The argument prev is a Boolean and is completely optional (defaults to false).

The argument params is an Object and is completely optional.

Pass true as the value for prev when you want to create a <button> or <a> that points to the previous page (e.g. it would generate a URL such as the one in the href attribute of <a href="/users?page=1&limit=10">Prev</a> if req.query.page is 2).

Pass an object for the value of params when you want to override querystring parameters – such as for filtering and sorting (e.g. it would generate a URL such as the one in the href attribute of <a href="/users?page=1&limit=10&sort=name">Sort By Name</a> if params is equal to { sort: 'name' }.

Note that if you pass only one argument with a type of Object, then it will generate a href with the current page and use the first argument as the value for params. This is useful if you only want to do something like change the filter or sort querystring param, but not increase or decrease the page number.

See the example below for an example of how implementation looks.

Arguments

  • req (required) – the request object returned from Express middleware invocation

Returned function arguments when invoked with req

  • prev (optional) – a Boolean to determine whether or not to increment the hyperlink returned by 1 (e.g. for "Next" page links)
  • params (optional) – an Object of querystring parameters that will override the current querystring in req.query (note that this will also override the page querystring value if page is present as a key in the params object) (e.g. if you want to make a link that allows the user to change the current querystring to sort by name, you would have params equal to { sort: 'name' })

paginate.hasPreviousPages

When you use the paginate middleware, it injects a view helper Boolean called hasPreviousPages as res.locals.hasPreviousPages, which you can use in your views for generating pagination <a>'s or <button>'s – this utilizes req.query.page > 1 to determine the Boolean's resulting value (representing if the query has a previous page of results)

paginate.hasNextPages(req)

When you use the paginate middleware, it injects a view helper function called hasNextPages as res.locals.hasPreviousPages, which you can use in your views for generating pagination <a>'s or <button>'s – if the function is executed, it returns a Boolean value (representing if the query has another page of results)

By default, the view helper paginate.hasNextPages is already executed with the inherited req variable, therefore it becomes a function capable of returning a Boolean when executed.

When executed with req, it will return a function that accepts two required arguments called pageCount and resultsCount.

Arguments

  • req (required) – the request object returned from Express middleware invocation

Returned function arguments when invoked with req

  • pageCount (required) – a Number representing the total number of pages for the given query executed on the page

paginate.getArrayPages(req)

Get all the page urls with limit. petronas contest 2015-10-29 12-35-52

Arguments

  • req (required) – the request object returned from Express middleware invocation

Returned function arguments when invoked with req

  • limit (optional) – Default: 3, a Number representing the total number of pages for the given query executed on the page.
  • pageCount (required) – a Number representing the total number of pages for the given query executed on the page.
  • currentPage (required) – a Number representing the current page.

Example with mongoose ODM (see example 2 for Sequelize ORM)

// # app.js

const express = require('express');
const paginate = require('express-paginate');
const app = express();

// keep this before all routes that will use pagination
app.use(paginate.middleware(10, 50));

app.get('/users', async (req, res, next) => {

  // This example assumes you've previously defined `Users`
  // as `const Users = db.model('Users')` if you are using `mongoose`
  // and that you are using Node v7.6.0+ which has async/await support
  try {

    const [ results, itemCount ] = await Promise.all([
      Users.find({}).limit(req.query.limit).skip(req.skip).lean().exec(),
      Users.count({})
    ]);

    const pageCount = Math.ceil(itemCount / req.query.limit);

    if (req.accepts('json')) {
      // inspired by Stripe's API response for list objects
      res.json({
        object: 'list',
        has_more: paginate.hasNextPages(req)(pageCount),
        data: results
      });
    } else {
      res.render('users', {
        users: results,
        pageCount,
        itemCount,
        pages: paginate.getArrayPages(req)(3, pageCount, req.query.page)
      });
    }

  } catch (err) {
    next(err);
  }

});

app.listen(3000);

Example 2 with Sequelize ORM

// # app.js

const express = require('express');
const paginate = require('express-paginate');
const app = express();

// keep this before all routes that will use pagination
app.use(paginate.middleware(10, 50));

app.get('/users', async (req, res, next) => {

  // This example assumes you've previously defined `Users`
  // as `const Users = sequelize.define('Users',{})` if you are using `Sequelize`
  // and that you are using Node v7.6.0+ which has async/await support

  router.get("/all_users", (req, res, next) => {
    db.User.findAndCountAll({limit: req.query.limit, offset: req.skip})
      .then(results => {
        const itemCount = results.count;
        const pageCount = Math.ceil(results.count / req.query.limit);
        res.render('users/all_users', {
          users: results.rows,
          pageCount,
          itemCount,
          pages: paginate.getArrayPages(req)(3, pageCount, req.query.page)
        });
    }).catch(err => next(err))
  });

});

app.listen(3000);
//- users.pug

h1 Users

//- this will simply generate a link to sort by name
//- note how we only have to pass the querystring param
//- that we want to modify here, not the entire querystring
a(href=paginate.href({ sort: 'name' })) Sort by name

//- this assumes you have `?age=1` or `?age=-1` in the querystring
//- so this will basically negate the value and give you
//- the opposite sorting order (desc with -1 or asc with 1)
a(href=paginate.href({ sort: req.query.age === '1' ? -1 : 1 })) Sort by age

ul
  each user in users
    li= user.email

include _paginate
//- _paginate.pug

//- This examples makes use of Bootstrap 3.x pagination classes

if paginate.hasPreviousPages || paginate.hasNextPages(pageCount)
  .navigation.well-sm#pagination
    ul.pager
      if paginate.hasPreviousPages
        li.previous
          a(href=paginate.href(true)).prev
            i.fa.fa-arrow-circle-left
            |  Previous
      if pages
        each page in pages
          a.btn.btn-default(href=page.url)= page.number
      if paginate.hasNextPages(pageCount)
        li.next
          a(href=paginate.href()).next
            | Next&nbsp;
            i.fa.fa-arrow-circle-right

License

MIT

More Repositories

1

express

Fast, unopinionated, minimalist web framework for node.
JavaScript
63,539
star
2

multer

Node.js middleware for handling `multipart/form-data`.
JavaScript
11,285
star
3

morgan

HTTP request logger middleware for node.js
JavaScript
7,790
star
4

session

Simple session middleware for Express
JavaScript
6,163
star
5

cors

Node.js CORS middleware
JavaScript
5,961
star
6

body-parser

Node.js body parsing middleware
JavaScript
5,376
star
7

expressjs.com

HTML
5,138
star
8

compression

Node.js compression middleware
JavaScript
2,722
star
9

csurf

CSRF token middleware
2,299
star
10

cookie-parser

Parse HTTP request cookies
JavaScript
1,907
star
11

generator

Express' application generator
JavaScript
1,803
star
12

serve-static

Serve static files
JavaScript
1,368
star
13

cookie-session

Simple cookie-based session middleware
JavaScript
1,104
star
14

vhost

virtual domain hosting
JavaScript
758
star
15

serve-favicon

favicon serving middleware
JavaScript
620
star
16

method-override

Override HTTP verbs.
JavaScript
614
star
17

response-time

Response time header for node.js
JavaScript
458
star
18

serve-index

Serve directory listings
JavaScript
435
star
19

errorhandler

Development-only error handler middleware
JavaScript
423
star
20

connect-multiparty

connect middleware for multiparty
JavaScript
347
star
21

express-namespace

Adds namespaced routing capabilities to Express
JavaScript
345
star
22

timeout

Request timeout middleware for Connect/Express
JavaScript
312
star
23

express-expose

Expose raw js, objects, and functions to the client-side (awesome for sharing utils, settings, current user data etc)
JavaScript
299
star
24

basic-auth-connect

Basic auth middleware for node and connect
JavaScript
129
star
25

domain-middleware

`uncaughtException` middleware for connect, base on `domain` module.
JavaScript
101
star
26

api-error-handler

Express error handlers for JSON APIs
JavaScript
100
star
27

flash

JavaScript
92
star
28

restful-router

Simple RESTful url router.
JavaScript
86
star
29

urlrouter

http url router, `connect` missing router middleware
JavaScript
59
star
30

discussions

Public discussions for the Express.js organization
55
star
31

vhostess

virtual host sub-domain mapping
JavaScript
24
star
32

connect-markdown

Auto convert markdown to html for connect.
JavaScript
20
star
33

expressjs.github.io

16
star
34

connect-rid

connect request id middleware
JavaScript
11
star
35

routification

DEPRECATED
JavaScript
10
star
36

mime-extended

DEPRECATED - Please use mime-types instead.
JavaScript
7
star
37

statusboard

A project status board for the Express community
6
star
38

.github

5
star
39

set-type

DEPRECATED - Please use mime-types instead.
JavaScript
5
star
40

security-wg

Express.js Security Working Group
4
star
41

Admin

Admin repository for the Express Organization, including pillarjs and jshttp
2
star