Skip to content

benjamin658/typeorm-cursor-pagination

Folders and files

NameName
Last commit message
Last commit date

Latest commit

fd1c97a · Mar 4, 2020

History

20 Commits
Mar 4, 2020
Mar 4, 2020
Mar 3, 2020
Mar 3, 2020
Mar 3, 2020
Mar 3, 2020
Mar 4, 2020
Mar 3, 2020
Mar 3, 2020
Mar 4, 2020
Mar 4, 2020

Repository files navigation

TypeORM Cursor Pagniation

Build Status Coverage Status npm version license

Cursor-based pagination works with TypeORM Query Builder.

Installation

npm install typeorm-cursor-pagination --save

Usage

Query first page without any cursor

import { getConnection } from "typeorm";
import { buildPaginator } from 'typeorm-cursor-pagination';

const queryBuilder = getConnection()
  .getRepository(User)
  .createQueryBuilder('user')
  .where("user.gender = :gender", { gender: 'male' });

const paginator = buildPaginator({
  entity: User,
  query: {
    limit: 10,
    order: 'ASC',
  },
});

// Pass queryBuilder as parameter to get paginate result.
const { data, cursor } = await paginator.paginate(queryBuilder);

The buildPaginator function has the following options:

  • entity [required]: TypeORM entity.
  • alias [optional]: alias of the query builder.
  • paginationKeys [optional]: array of the fields to be used for the pagination, default is id.
  • query [optional]:
    • limit: limit the number of records returned, default is 100.
    • order: ASC or DESC, default is DESC.
    • beforeCursor: the before cursor.
    • afterCursor: the after cursor.

paginator.paginate(queryBuilder) returns the entities and cursor for next iteration

interface PagingResult<Entity> {
  data: Entity[];
  cursor: Cursor;
}

interface Cursor {
  beforeCursor: string | null;
  afterCursor: string | null;
}

Query next page by afterCursor

const nextPaginator = buildPaginator({
  entity: User,
  query: {
    limit: 10,
    order: 'ASC',
    afterCursor: cursor.afterCursor,
  },
});

Query prev page by beforeCursor

const prevPaginator = buildPaginator({
  entity: User,
  query: {
    limit: 10,
    order: 'ASC',
    beforeCursor: cursor.beforeCursor,
  },
});

Integration Test with Docker

To start a integration test, run the following command:

npm run test:docker

License

© Ben Hu (benjamin658), 2020-NOW

Released under the MIT License