From 7f0beeb5a78f292bd191dbfa56df894b312afdd7 Mon Sep 17 00:00:00 2001 From: zkldi Date: Wed, 15 Mar 2023 10:20:00 +0000 Subject: [PATCH] feat: contains operator (#536) --- README.md | 6 +++++- src/filter.ts | 12 ++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index b28ee43..70940f0 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Pagination and filtering helper method for TypeORM repositories or query builder - Sort by multiple columns - Search across columns - Select columns -- Filter using operators (`$eq`, `$not`, `$null`, `$in`, `$gt`, `$gte`, `$lt`, `$lte`, `$btw`, `$ilike`, `$sw`) +- Filter using operators (`$eq`, `$not`, `$null`, `$in`, `$gt`, `$gte`, `$lt`, `$lte`, `$btw`, `$ilike`, `$sw`, `$contains`) - Include relations and nested relations - Virtual column support @@ -406,6 +406,10 @@ Filter operators must be whitelisted per column in `PaginateConfig`. `?filter.createdAt=$btw:2022-02-02,2022-02-10` where column `createdAt` is between the dates `2022-02-02` and `2022-02-10` +`?filter.roles=$contains:Moderator` where column `roles` is an array and contains the value "Moderator". + +`?filter.roles=$contains:Moderator,Admin` where column `roles` is an array and contains the values "Moderator" and "Admin". + ## Multi Filters Multi filters are filters that can be applied to a single column with a comparator. As for single filters, multi filters must be whitelisted per column in `PaginateConfig`. diff --git a/src/filter.ts b/src/filter.ts index 80672e1..5a212ee 100644 --- a/src/filter.ts +++ b/src/filter.ts @@ -1,16 +1,17 @@ import { values } from 'lodash' import { + ArrayContains, + Between, Brackets, Equal, FindOperator, + ILike, In, - MoreThan, - MoreThanOrEqual, IsNull, LessThan, LessThanOrEqual, - Between, - ILike, + MoreThan, + MoreThanOrEqual, Not, SelectQueryBuilder, } from 'typeorm' @@ -35,6 +36,7 @@ export enum FilterOperator { BTW = '$btw', ILIKE = '$ilike', SW = '$sw', + CONTAINS = '$contains', } export function isOperator(value: unknown): value is FilterOperator { @@ -73,6 +75,7 @@ export const OperatorSymbolToFunction = new Map< [FilterOperator.ILIKE, ILike], [FilterSuffix.NOT, Not], [FilterOperator.SW, ILike], + [FilterOperator.CONTAINS, ArrayContains], ]) type Filter = { comparator: FilterComparator; findOperator: FindOperator } @@ -264,6 +267,7 @@ export function parseFilter( params.findOperator = OperatorSymbolToFunction.get(token.operator)(...token.value.split(',')) break case FilterOperator.IN: + case FilterOperator.CONTAINS: // <- IN and CONTAINS are identically handled. params.findOperator = OperatorSymbolToFunction.get(token.operator)(token.value.split(',')) break case FilterOperator.ILIKE: