Skip to content

ArtashMardoyan/koa-pagination

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

koa-pagination-v2

Pagination middleware for Koa.

npm version npm downloads install size MIT License

Installation

Install the package via yarn:

> yarn add koa-pagination-v2

or via npm:

> npm install koa-pagination-v2 --save

Configuration

The middleware can be configured with the following parameters:

  • defaultLimit: Default number of items allowed per page (10 by default).
  • maximumLimit: Maximum number of items allowed per page (100 by default).

You can change the defaults by doing:

pagination({ defaultLimit: 20, maximumLimit: 50 });

Usage

const app = new (require('koa'))();
const pagination = require('koa-pagination-v2');

const { User } = require('../models');

app.use(pagination({ defaultLimit: 20, maximumLimit: 50 }));

app.get('/', async ctx => {
    const { limit, offset, pageable } = ctx.state.paginate;

    const { rows: users, count: total } = await User.findAndCountAll({
        offset,
        limit
    });

    return ctx.ok({ users, _meta: pageable(total) });
});

app.listen(3000);

Request example

> http://localhost:3000/v1/users?page=1&limit=10

Response example

{
  "statusName": "OK",
  "statusCode": 200,
  "data": [
    {
      "id": "b79398ef-acf2-4e67-af1b-1482b79886b1",
      "firstName": "Artash",
      "lastName": "Mardoyan",
      "updatedAt": "2022-07-11T08:24:38.337Z",
      "createdAt": "2022-07-11T08:17:05.356Z"
    },
    {
      "id": "b79398ef-acf2-4e67-af1b-1482b79886b2",
      "firstName": "Gagik",
      "lastName": "Alikhanyan",
      "updatedAt": "2022-07-11T08:24:38.337Z",
      "createdAt": "2022-07-11T08:17:05.356Z"
    },
    {
      "id": "b79398ef-acf2-4e67-af1b-1482b79886b3",
      "firstName": "Rafik",
      "lastName": "Abgaryan",
      "updatedAt": "2022-07-11T08:24:38.337Z",
      "createdAt": "2022-07-11T08:17:05.356Z"
    },
    {
      "id": "b79398ef-acf2-4e67-af1b-1482b79886b3",
      "firstName": "Tsolak",
      "lastName": "Harutyunyan",
      "updatedAt": "2022-07-11T08:24:38.337Z",
      "createdAt": "2022-07-11T08:17:05.356Z"
    }
  ],
  "_meta": {
    "offset": 0,
    "limit": 10,
    "total": 4,
    "pageCount": 4,
    "currentPage": 1,
    "hasPrev": false,
    "hasNext": false
  }
}

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published