项目作者: benjamin658

项目描述 :
Cursor-based pagination works with TypeORM Query Builder.
高级语言: TypeScript
项目地址: git://github.com/benjamin658/typeorm-cursor-pagination.git
创建时间: 2020-03-02T07:55:32Z
项目社区:https://github.com/benjamin658/typeorm-cursor-pagination

开源协议:MIT License

下载


TypeORM Cursor Pagination

Build Status
codecov
npm version
Maintainability
license

Cursor-based pagination works with TypeORM Query Builder.

Why or What is Cursor-Based Pagination

If this project is helpful to you, I truly appreciate you all for your stars ⭐⭐⭐ and contributions 💪💪💪.

Installation

npm install typeorm-cursor-pagination --save

Usage

Query first page without any cursor

  1. import { getConnection } from "typeorm";
  2. import { buildPaginator } from 'typeorm-cursor-pagination';
  3. const queryBuilder = getConnection()
  4. .getRepository(User)
  5. .createQueryBuilder('user')
  6. .where("user.gender = :gender", { gender: 'male' });
  7. const paginator = buildPaginator({
  8. entity: User,
  9. paginationKeys: ['id'],
  10. query: {
  11. limit: 10,
  12. order: 'ASC',
  13. },
  14. });
  15. // Pass queryBuilder as parameter to get paginate result.
  16. 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 the next iteration

  1. interface PagingResult<Entity> {
  2. data: Entity[];
  3. cursor: Cursor;
  4. }
  5. interface Cursor {
  6. beforeCursor: string | null;
  7. afterCursor: string | null;
  8. }

Query next page by afterCursor

  1. const nextPaginator = buildPaginator({
  2. entity: User,
  3. paginationKeys: ['id'],
  4. query: {
  5. limit: 10,
  6. order: 'ASC',
  7. afterCursor: cursor.afterCursor,
  8. },
  9. });
  10. const { data, cursor } = await nextPaginator.paginate(queryBuilder);

Query prev page by beforeCursor

  1. const prevPaginator = buildPaginator({
  2. entity: User,
  3. paginationKeys: ['id'],
  4. query: {
  5. limit: 10,
  6. order: 'ASC',
  7. beforeCursor: cursor.beforeCursor,
  8. },
  9. });
  10. const { data, cursor } = await prevPaginator.paginate(queryBuilder);

Integration Test with Docker

To start an integration test, run the following command:

npm run test:docker

Contributing

All contributions are welcome, open a pull request or issue any time.

Commit your changes using a descriptive commit message that follows commit message conventions.

License

© Ben Hu (benjamin658), 2021-NOW

Released under the MIT License