diff --git a/README.md b/README.md index 6edab9c..c3af057 100644 --- a/README.md +++ b/README.md @@ -202,3 +202,17 @@ const paginateConfig: PaginateConfig { filterableColumns: { age: [FilterOperator.EQ, FilterOperator.IN] } } ``` + +## Usage with Query Builder + +### Example + +```typescript +const queryBuilder = repo + .createQueryBuilder('cats') + .leftJoinAndSelect('cats.owner', 'owner') + .where('cats.color = :color', { color: 'white' }) + .andWhere('cats.owner = :ownerId', { ownerId }) + +const result = await paginate(query, queryBuilder, config) +``` diff --git a/src/paginate.spec.ts b/src/paginate.spec.ts index bd691b4..21737bd 100644 --- a/src/paginate.spec.ts +++ b/src/paginate.spec.ts @@ -1,4 +1,4 @@ -import { createConnection, Repository, Column, In } from 'typeorm' +import { createConnection, Repository, Column, In, createQueryBuilder, Connection } from 'typeorm' import { Paginated, paginate, @@ -31,11 +31,12 @@ export class CatEntity { } describe('paginate', () => { + let connection: Connection let repo: Repository let cats: CatEntity[] beforeAll(async () => { - const connection = await createConnection({ + connection = await createConnection({ type: 'sqlite', database: ':memory:', synchronize: true, @@ -68,6 +69,44 @@ describe('paginate', () => { expect(result.data).toStrictEqual(cats.slice(0, 1)) }) + it('should accept a query builder', async () => { + const config: PaginateConfig = { + sortableColumns: ['id'], + defaultSortBy: [['id', 'ASC']], + defaultLimit: 1, + } + const query: PaginateQuery = { + path: '', + } + + const queryBuilder = await repo.createQueryBuilder('cats') + + const result = await paginate(query, queryBuilder, config) + + expect(result.data).toStrictEqual(cats.slice(0, 1)) + }) + + it('should accept a query builder with custom condition', async () => { + const config: PaginateConfig = { + sortableColumns: ['id'], + defaultSortBy: [['id', 'ASC']], + defaultLimit: 1, + } + const query: PaginateQuery = { + path: '', + } + + const queryBuilder = await connection + .createQueryBuilder() + .select('cats') + .from(CatEntity, 'cats') + .where('cats.color = :color', { color: 'white' }) + + const result = await paginate(query, queryBuilder, config) + + expect(result.data).toStrictEqual(cats.slice(3, 4)) + }) + it('should default to page 1, if negative page is given', async () => { const config: PaginateConfig = { sortableColumns: ['id'], diff --git a/src/paginate.ts b/src/paginate.ts index c495f99..ff12926 100644 --- a/src/paginate.ts +++ b/src/paginate.ts @@ -113,7 +113,7 @@ export function getFilterTokens(raw: string): string[] { } function parseFilter(query: PaginateQuery, config: PaginateConfig) { - const filter = {} + const filter: { [columnName: string]: FindOperator } = {} for (const column of Object.keys(query.filter)) { if (!(column in config.filterableColumns)) { continue