Skip to content

Commit 93ba636

Browse files
committed
Add support for filtering by less/greater and less than/greater than
1 parent 2a399ca commit 93ba636

File tree

2 files changed

+49
-6
lines changed

2 files changed

+49
-6
lines changed

src/paginateable.entity.ts

+3-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { BadRequestException } from '@nestjs/common';
2-
import { BaseEntity, ObjectType, FindManyOptions, In, Equal } from 'typeorm';
2+
import { BaseEntity, ObjectType, FindManyOptions } from 'typeorm';
33
import { PaginationParams } from './pagination.decorator';
44
import { Pagination } from './pagination.interface';
5+
import { getFindOperator } from './utils/getFindOperator';
56

67
export abstract class PaginateableBaseEntity extends BaseEntity {
78
/**
@@ -49,11 +50,7 @@ export abstract class PaginateableBaseEntity extends BaseEntity {
4950
const filterQuery = {};
5051

5152
toFilter.forEach(([key, value]) => {
52-
if (Array.isArray(value)) {
53-
filterQuery[key] = In(value);
54-
} else {
55-
filterQuery[key] = Equal(value);
56-
}
53+
filterQuery[key] = getFindOperator(value);
5754
});
5855

5956
query = {

src/utils/getFindOperator.ts

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { Equal, FindOperator, In, LessThan, LessThanOrEqual, MoreThan, MoreThanOrEqual } from 'typeorm';
2+
3+
enum ComparatorTypeEnum {
4+
GREATER_THAN= '>',
5+
LESS_THAN = '<',
6+
GREATER_THAN_OR_EQUAL = '>=',
7+
LESS_THAN_OR_EQUAL = '<=',
8+
EQUAL = '=',
9+
}
10+
11+
const isCompareSign = char => {
12+
return Object.values(ComparatorTypeEnum).includes(char as ComparatorTypeEnum);
13+
};
14+
15+
export function getFindOperator(value: any): FindOperator<any> {
16+
if (Array.isArray(value)) {
17+
return In(value);
18+
}
19+
20+
const compareSign = value
21+
.substr(0, 2)
22+
.split('')
23+
.filter(isCompareSign)
24+
.join('');
25+
26+
const realValue = value.substr(compareSign.length);
27+
28+
switch (compareSign) {
29+
case ComparatorTypeEnum.GREATER_THAN: {
30+
return MoreThan(realValue);
31+
}
32+
case ComparatorTypeEnum.GREATER_THAN_OR_EQUAL: {
33+
return MoreThanOrEqual(realValue);
34+
}
35+
case ComparatorTypeEnum.LESS_THAN: {
36+
return LessThan(realValue);
37+
}
38+
case ComparatorTypeEnum.LESS_THAN_OR_EQUAL: {
39+
return LessThanOrEqual(realValue);
40+
}
41+
case ComparatorTypeEnum.EQUAL:
42+
default: {
43+
return Equal(realValue);
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)