{"id":14989448,"url":"https://github.com/panderalabs/koa-pageable","last_synced_at":"2025-07-26T11:19:08.073Z","repository":{"id":57134957,"uuid":"122219356","full_name":"panderalabs/koa-pageable","owner":"panderalabs","description":"Pagination framework for Koa (inspired by Spring Data)","archived":false,"fork":false,"pushed_at":"2020-06-02T23:49:24.000Z","size":5333,"stargazers_count":13,"open_issues_count":15,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-25T21:14:04.819Z","etag":null,"topics":["javascript-library","koajs","nodejs","pagination"],"latest_commit_sha":null,"homepage":"https://panderalabs.github.io/koa-pageable/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/panderalabs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-02-20T15:49:57.000Z","updated_at":"2022-10-26T11:16:26.000Z","dependencies_parsed_at":"2022-09-04T07:30:41.901Z","dependency_job_id":null,"html_url":"https://github.com/panderalabs/koa-pageable","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panderalabs%2Fkoa-pageable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panderalabs%2Fkoa-pageable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panderalabs%2Fkoa-pageable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panderalabs%2Fkoa-pageable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/panderalabs","download_url":"https://codeload.github.com/panderalabs/koa-pageable/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248115995,"owners_count":21050324,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript-library","koajs","nodejs","pagination"],"created_at":"2024-09-24T14:18:23.311Z","updated_at":"2025-04-12T01:30:39.984Z","avatar_url":"https://github.com/panderalabs.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.org/panderalabs/koa-pageable.svg?branch=master)](https://travis-ci.org/panderalabs/koa-pageable)\n[![Greenkeeper badge](https://badges.greenkeeper.io/panderalabs/koa-pageable.svg)](https://greenkeeper.io/)\n\n* [About](#about)\n* [Overview](#overview)\n  * [Request](#request)\n    * [Query parameters](#query-parameters)\n      * [Pageable](#pageable)\n      * [Sort](#sort)\n    * [Errors](#errors)\n  * [Response](#response)\n    * [All Page types](#all-page-types)\n      * [Map Method](#map-method)\n    * [ArrayPage](#arraypage)\n    * [IndexedPage](#indexedpage)\n    * [IndexablePage](#indexablepage)\n    * [Output Format](#output-format)\n      * [Non\\-Indexed](#non-indexed)\n      * [Indexed](#indexed)\n* [Getting Started](#getting-started)\n  * [Installation](#installation)\n    * [npm](#npm)\n    * [yarn](#yarn)\n  * [Requirements](#requirements)\n  * [Examples](#examples)\n    * [Router](#router)\n    * [Data Access](#data-access)\n* [API Documentation](#api-documentation)\n\n# About\n`koa-pageable` is middleware for pagination in [Koa](https://github.com/koajs/koa) inspired by  [Spring Data](http://docs.spring.io/spring-data/commons/docs/current/reference/html/)'s Pagination support.\n\nIt allows clients of your API to easily request subsets of your data by providing query parameters to specify the amount, order, and formatting of the requested data. For instance, if you had an endpoint `/people` backed by a data store containing 1000 people records, `koa-pageable` allows a client to request the data be broken up into 10 person pages, and to receive 2nd page of people sorted by their lastname (`GET /people?page=1\u0026size=10\u0026sort=lastname`)\n\n# Overview  \n## Request \n### Query parameters\nWhen enabled this middleware parses request query parameters from `ctx.query` into an instance of `Pageable`. \n\n**These values are:** \n\nParameter | Default Value | Description  \n----------|---------------|------------\n`page`    | `0`           | The 0-indexed page to be retrieved \n`size`    | `10`          | Maximum number of elements to be included in the retrieved page  \n`sort`    | `undefined`   | Properties that should be sorted, in the specified order. Properties are separated by a `,` and directions are separated with a `:`. Valid directions are `asc` and `desc` and if not specified, direction defaults to `asc`. For example to sort by `lastname` ascending, then `firstname` descending: `?sort=lastname,firstname:desc`|         \n`indexed` | `false`       | If the underlying content supports it (i.e. has an `id` property) return results in indexed format. Which is an array of ids and a map of {id : content item}\n\n#### Pageable\nThe `Pageable` object created from the query parameters contains two integers, `page` \u0026 `size`, an optional `Sort` instance, and an `indexed` boolean.\nThis `pageable` instance should  be passed to your data access layer, and its content should be used to restrict the returned data to the data specified by the `pageable`.\n\n#### Sort\n`Sort` is a collection of `property` and `direction`( `asc` or `desc`) pairs.\nEach `sort` instance has a `forEach(callback(property,direction))` method that invokes `callback` for each `property`/`direction` pair in the `sort`  \n\n### Errors\nIf the `page` or `size` query parameter are not specified as valid numbers, a `NumberFormatError` will be thrown. If the sort direction is specified as anything other than `asc` or `desc` (e.g. `sort=lastName:foo`) then an `InvalidSortError` will be thrown.\n\n## Response\nThe data returned from a using this middleware should be an instance of a subclass of `Page`.  \n\n### All Page types\nAll `Page` types contain the following properties:\n\nProperty           | Description\n-------------------|------------\n`number`           | The number of the current page (should match `pageable.page`)\n`size`             | The number of elements requested to be included in the current page (should match `pageable.size`)\n`numberOfElements` | The number of elements actually returned in this page. If \u003c size, indicates that this is the last page\n`totalElements`    | Total number of elements available\n`totalPages`       | Total number of pages available\n`sort`             | The sort criteria (should match `pageable.sort`)\n`first`            | True if this is the first page \n`last`             | True if this is the final page \n\nYou may have noticed that the above list does not define a property containing the actual content to be returned. \nThis is because there are multiple `Page` implementations which represent the actual content items in different formats.\n\n#### Map Method\nAll Page types also provide a `map(iteratee)` method. This method iterates over each content item in the page and invokes iteratee with the content item as the argument, \nallowing easy transformation from a `Page\u003cX\u003e` to a `Page\u003cY\u003e`. This is useful, for instance, if you wish to return a different object \nfrom your `router` than the type returned from your data layer. \n\n### ArrayPage\nA `Page` of content items represented as an array. An `ArrayPage` contains all of the properties above plus:\n\nProperty  | Description\n----------|------------\n`content` | Array of content ordered as per `pageable.sort`\n  \n### IndexedPage\nAn `IndexedPage` represents the returned content as an array of `ids` and a corresponding `index`, which is a map of `{id: content item}`.\nAn `IndexedPage` contains all of the standard page properties plus:\n\nProperty | Description\n---------|------------\n`ids`    | Array of ids ordered as per `pageable.sort`\n`index`  | Map of id to content item  \n\n\n### IndexablePage\nAn `IndexablePage` is a special case of `Page`, it internally stores its data in the same format as a `ArrayPage` but allows the client some level of control over the response structure.  \nUpon serialization (i.e. invoking `toJSON()`) if the `pageable.indexed` value is set to `true`, the result will be serialized as an `IndexedPage` (else as an `ArrayPage`). \nIn order to support this automatic conversion, the underlying content items _must_ each contain an `id` property.\n\n### Output Format \n\n#### Non-Indexed\n`GET /people?page=2\u0026size=2\u0026sort=firstname,lastname:desc\u0026indexed=false`\n\n```javascript\n{            \n  \"number\": 2,\n  \"size\": 2,\n  \"sort\": [\n    {\n      \"direction\": \"asc\",\n      \"property\": \"firstname\"\n    },\n    {\n      \"direction\": \"lastname\",\n      \"property\": \"desc\"\n    }\n  ],\n  \"totalElements\": 18,\n  \"totalPages\": 9,\n  \"first\": false,\n  \"last\": false,\n  \"indexed\": false,\n  \"content\": [\n    {\n      \"id\": 202,\n      \"firstName\": \"Bob\",\n      \"lastName\": \"Smith\"\n    },\n    {\n      \"id\": 200,\n      \"firstName\": \"Bob\",\n      \"lastName\": \"Jones\"\n    }\n  ],\n  \"numberOfElements\": 2\n}\n```\n#### Indexed\n`GET /people?page=2\u0026size=2\u0026sort=firstname,lastname:desc\u0026indexed=true`\n\n```javascript\n{\n  \"number\": 2,\n  \"size\": 2,\n  \"sort\": [\n    {\n      \"direction\": \"desc\",\n      \"property\": \"id\"\n    },\n    {\n      \"direction\": \"asc\",\n      \"property\": \"createdTimestamp\"\n    }\n  ],\n  \"totalElements\": 18,\n  \"totalPages\": 9,\n  \"first\": false,\n  \"last\": false,\n  \"ids\": [\n    202,\n    200\n  ],\n  \"index\": {\n    \"200\": {\n      \"id\": 200,\n      \"firstName\": \"Frank\",\n      \"lastName\": \"Jones\"\n    },\n    \"202\": {\n      \"id\": 202,\n      \"firstName\": \"Bob\",\n      \"lastName\": \"Jones\"\n    }\n  },\n  \"numberOfElements\": 2\n}\n```\n\n# Getting Started\n\n## Installation\n### npm\n```\nnpm install @panderalabs/koa-pageable\n```\n### yarn\n```\nyarn add @panderalabs/koa-pageable\n```\n\n## Requirements\nRequires `node` \u003e= `8.2`, as `koa-pageable` makes use of async/await. [Flow](http://flowtype.org) bindings are also provided.   \nNote: The following examples includes optional flow type annotations for clarity.\n\n`koa-pageable` is a convenient library for managing conversion of user intent (via request parameters) into a `Pageable` object, but it is still your responsibility to implement that intention when accessing data. You are responsible for ensuring that your data access tier properly implements the pagination and/or sorting, and for creating the `Page` instances to be returned. The exact approach for doing so will differ based on your chose Data Access framework. \n\n## Examples\n### Router\n```javascript\n// @flow\nimport { Pageable, IndexedPage, paginate } from '@panderalabs/koa-pageable';\nimport Koa from 'koa';\n\nvar app = new Koa();\napp.use(paginate);\n\napp.use(async ctx =\u003e {\n  // the pageable created from query parameters will be stored in ctx.state.pageable\n  const pageable: Pageable = ctx.state.pageable;\n  // pass the pageable down into any service and data access tiers, and use its properties to retrieve the appropriate data and return it as a Page\n  const result: IndexedPage\u003cPerson\u003e = service.getData(pageable);\n});\n```\n\n### Data Access\nExample of using `pageable` as input to a query, and `Page` as the response type. \nThis example is based on [Objection](http://vincit.github.io/objection.js/) but should be translatable to any data access / ORM framework.\n\n```javascript\n// @flow\nimport { IndexablePage, Pageable, Sort, } from '@panderalabs/koa-pageable';\nimport type { QueryBuilder } from 'objection';\n\nfunction getData(pageable: Pageable): IndexablePage\u003cFoo\u003e {\n  const pageNumber = pageable.page;\n  const pageSize = pageable.size;\n  const sort: Sort  = pageable.sort;\n \n  const queryBuilder: QueryBuilder = Person.query().where('age', '\u003e', 21).page(pageNumber, pageSize);\n  \n  //If there is a sort, add each order element to the query's `orderBy`\n  if (sort) {\n    sort.forEach((property, direction) =\u003e queryBuilder.orderBy(property, direction));\n  }  \n  const result = await query.execute();\n  \n  return new IndexablePage(result.results, result.total, pageable); \n}\n```\n\n# API Documentation\nhttps://panderalabs.github.io/koa-pageable/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpanderalabs%2Fkoa-pageable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpanderalabs%2Fkoa-pageable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpanderalabs%2Fkoa-pageable/lists"}