fix: add query builder example

This commit is contained in:
ppetzold 2022-02-06 19:52:38 +01:00
parent 7094810bd7
commit faac1b379d
3 changed files with 56 additions and 3 deletions

View File

@ -202,3 +202,17 @@ const paginateConfig: PaginateConfig<CatEntity> {
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<CatEntity>(query, queryBuilder, config)
```

View File

@ -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<CatEntity>
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<CatEntity> = {
sortableColumns: ['id'],
defaultSortBy: [['id', 'ASC']],
defaultLimit: 1,
}
const query: PaginateQuery = {
path: '',
}
const queryBuilder = await repo.createQueryBuilder('cats')
const result = await paginate<CatEntity>(query, queryBuilder, config)
expect(result.data).toStrictEqual(cats.slice(0, 1))
})
it('should accept a query builder with custom condition', async () => {
const config: PaginateConfig<CatEntity> = {
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<CatEntity>(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<CatEntity> = {
sortableColumns: ['id'],

View File

@ -113,7 +113,7 @@ export function getFilterTokens(raw: string): string[] {
}
function parseFilter<T>(query: PaginateQuery, config: PaginateConfig<T>) {
const filter = {}
const filter: { [columnName: string]: FindOperator<string> } = {}
for (const column of Object.keys(query.filter)) {
if (!(column in config.filterableColumns)) {
continue