fix: or filters are grouped together (#774)

This commit is contained in:
Jonathan Chapman 2023-10-07 11:50:19 -06:00 committed by GitHub
parent 5f64f1ccbf
commit c47973d063
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 2 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ coverage/
.DS_Store
npm-debug.log
.history
.idea/

View File

@ -313,11 +313,26 @@ export function addFilter<T>(
filterableColumns?: { [column: string]: (FilterOperator | FilterSuffix)[] | true }
): SelectQueryBuilder<T> {
const filter = parseFilter(query, filterableColumns)
return qb.andWhere(
const filterEntries = Object.entries(filter)
const orFilters = filterEntries.filter(([_, value]) => value.some((v) => v.comparator === '$or'))
const andFilters = filterEntries.filter(([_, value]) => value.some((v) => v.comparator !== '$or'))
qb.andWhere(
new Brackets((qb: SelectQueryBuilder<T>) => {
for (const column in filter) {
for (const [column] of orFilters) {
addWhereCondition(qb, column, filter)
}
})
)
qb.andWhere(
new Brackets((qb: SelectQueryBuilder<T>) => {
for (const [column] of andFilters) {
addWhereCondition(qb, column, filter)
}
})
)
return qb
}

View File

@ -2129,6 +2129,33 @@ describe('paginate', () => {
)
})
it('should return result based on two ors and an and with two cats', async () => {
const config: PaginateConfig<CatEntity> = {
sortableColumns: ['id'],
filterableColumns: {
age: [FilterOperator.BTW],
name: true,
color: true,
},
}
const query: PaginateQuery = {
path: '',
filter: {
name: '$or:Milo',
color: '$or:white',
age: '$btw:1,10',
},
}
const result = await paginate<CatEntity>(query, catRepo, config)
expect(result.data).toStrictEqual(
cats.filter((cat) => (cat.name === 'Milo' || cat.color === 'white') && cat.age)
)
expect(result.links.current).toBe(
'?page=1&limit=20&sortBy=id:ASC&filter.name=$or:Milo&filter.color=$or:white&filter.age=$btw:1,10'
)
})
it("should return all columns if select doesn't contain all primary columns", async () => {
const config: PaginateConfig<CatEntity> = {
sortableColumns: ['id', 'name'],