|
| 1 | +--- |
| 2 | +title: Custom Filters |
| 3 | +--- |
| 4 | + |
| 5 | +In addition to the built in filters, you can also define custom filtering operations. |
| 6 | + |
| 7 | +There are 2 types of custom filters: |
| 8 | + |
| 9 | +- Global type-based filters, that automatically work on all fields of a given GraphQL type. |
| 10 | +- Custom entity-specific filters, that are custom-tailored for DTOs and do not require a specific backing field (more on |
| 11 | + that below). |
| 12 | + |
| 13 | +[//]: # (TODO Add link to page) |
| 14 | +:::important |
| 15 | + |
| 16 | +This page describes how to implement custom filters at the GraphQL Level. The persistence layer needs to support them as |
| 17 | +well. For now, only TypeOrm is implemented. See here: |
| 18 | + |
| 19 | +- [TypeOrm Custom Filters](/docs/persistence/typeorm/custom-filters) |
| 20 | + |
| 21 | +::: |
| 22 | + |
| 23 | +## Global type-based filters |
| 24 | + |
| 25 | +Type based filters are applied globally to all DTOs, based only on the underlying GraphQL Type. |
| 26 | + |
| 27 | +### Extending the existing filters |
| 28 | + |
| 29 | +Let's assume our persistence layer exposes a `isMultipleOf` filter which allows us to filter numeric fields and choose |
| 30 | +only multiples of a user-supplied value. In order to expose that filter on all numeric GraphQL fields, we can do the |
| 31 | +following in any typescript file (ideally this should run before the app is initialized): |
| 32 | + |
| 33 | +```ts |
| 34 | +import { registerTypeComparison } from '@nestjs-query/query-graphql'; |
| 35 | +import { IsBoolean, IsInt } from 'class-validator'; |
| 36 | +import { Float, Int } from '@nestjs/graphql'; |
| 37 | + |
| 38 | +registerTypeComparison(Number, 'isMultipleOf', { FilterType: Number, GqlType: Int, decorators: [IsInt()] }); |
| 39 | +registerTypeComparison(Int, 'isMultipleOf', { FilterType: Number, GqlType: Int, decorators: [IsInt()] }); |
| 40 | +registerTypeComparison(Float, 'isMultipleOf', { FilterType: Number, GqlType: Int, decorators: [IsInt()] }); |
| 41 | + |
| 42 | +// Note, this also works |
| 43 | +// registerTypeComparison([Number, Int, Float], 'isMultipleOf', { FilterType: Number, GqlType: Int, decorators: [IsInt()] }); |
| 44 | +``` |
| 45 | + |
| 46 | +Where: |
| 47 | + |
| 48 | +- FilterType is the typescript type of the filter |
| 49 | +- GqlType is the GraphQL type that will be used in the schema |
| 50 | +- decorators represents a list of decorators that will be applied to the filter class at the specific field used for the |
| 51 | + operation, used e.g. for validation purposes |
| 52 | + |
| 53 | +The above snippet patches the existing Number/Int/Float FieldComparisons so that they expose the new |
| 54 | +field/operation `isMultipleOf`. Example: |
| 55 | + |
| 56 | +```graphql |
| 57 | +input NumberFieldComparison { |
| 58 | + is: Boolean |
| 59 | + isNot: Boolean |
| 60 | + eq: Float |
| 61 | + neq: Float |
| 62 | + gt: Float |
| 63 | + gte: Float |
| 64 | + lt: Float |
| 65 | + lte: Float |
| 66 | + in: [Float!] |
| 67 | + notIn: [Float!] |
| 68 | + between: NumberFieldComparisonBetween |
| 69 | + notBetween: NumberFieldComparisonBetween |
| 70 | + isMultipleOf: Int |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +### Defining a filter on a custom scalar |
| 75 | + |
| 76 | +Let's assume we have a custom scalar, to represent e.g. a geo point (i.e. {lat, lng}): |
| 77 | + |
| 78 | +```ts |
| 79 | +@Scalar('Point', (type) => Object) |
| 80 | +export class PointScalar implements CustomScalar<any, any> { |
| 81 | + description = 'Point custom scalar type'; |
| 82 | + |
| 83 | + parseValue(value: any): any { |
| 84 | + return { lat: value.lat, lng: value.lng }; |
| 85 | + } |
| 86 | + |
| 87 | + serialize(value: any): any { |
| 88 | + return { lat: value.lat, lng: value.lng }; |
| 89 | + } |
| 90 | + |
| 91 | + parseLiteral(ast: ValueNode): any { |
| 92 | + if (ast.kind === Kind.OBJECT) { |
| 93 | + return ast.fields; |
| 94 | + } |
| 95 | + return null; |
| 96 | + } |
| 97 | +} |
| 98 | +``` |
| 99 | + |
| 100 | +Now, we want to add a radius filter to all Point scalars. A radius filter is a filter that returns all entities whose |
| 101 | +location is within a given distance from another point. |
| 102 | + |
| 103 | +First, we need to define the filter type: |
| 104 | + |
| 105 | +```ts |
| 106 | +@InputType('RadiusFilter') |
| 107 | +export class RadiusFilter { |
| 108 | + @Field(() => Number) |
| 109 | + lat!: number; |
| 110 | + |
| 111 | + @Field(() => Number) |
| 112 | + lng!: number; |
| 113 | + |
| 114 | + @Field(() => Number) |
| 115 | + radius!: number; |
| 116 | +} |
| 117 | +``` |
| 118 | + |
| 119 | +Then, we need to register said filter: |
| 120 | + |
| 121 | +```ts |
| 122 | +registerTypeComparison(PointScalar, 'distanceFrom', { |
| 123 | + FilterType: RadiusFilter, |
| 124 | + GqlType: RadiusFilter, |
| 125 | +}); |
| 126 | +``` |
| 127 | + |
| 128 | +The above snippet creates a new comparison type for the Point scalar and adds the distanceFrom operations to it. |
| 129 | +Example: |
| 130 | + |
| 131 | +```graphql |
| 132 | +input RadiusFilter { |
| 133 | + lat: Float! |
| 134 | + lng: Float! |
| 135 | + radius: Float! |
| 136 | +} |
| 137 | + |
| 138 | +input PointScalarFilterComparison { |
| 139 | + distanceFrom: RadiusFilter |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +Now, our persistence layer will be able to receive this new `distanceFrom` key for every property that is represented as |
| 144 | +a Point scalar. |
| 145 | + |
| 146 | +:::important |
| 147 | + |
| 148 | +If the shape of the filter at the GraphQL layer is different from what the persistence layer expects, remember to use |
| 149 | +an [Assembler and its convertQuery method!](/docs/concepts/advanced/assemblers#converting-the-query) |
| 150 | + |
| 151 | +::: |
| 152 | + |
| 153 | +### Disabling a type-based custom filter on specific fields of a DTO |
| 154 | + |
| 155 | +Global filters are fully compatible with the [allowedComparisons](/docs/graphql/dtos/#example---allowedcomparisons) |
| 156 | +option of the `@FilterableField` decorator. |
| 157 | + |
| 158 | +## DTO-based custom filters |
| 159 | + |
| 160 | +These custom filters are explicitly registered on a single DTO field, rather than at the type level. This can be useful |
| 161 | +if the persistence layer exposes some specific filters only on some entities (e.g. "Filter all projects who more than 5 |
| 162 | +pending tasks" where we need to compute the number of pending tasks using a SQL sub-query in the where clause, instead |
| 163 | +of having a computed field in the project entity). |
| 164 | + |
| 165 | +:::important |
| 166 | + |
| 167 | +DTO-based custom filters cannot be registered on existing DTO filterable fields, use type-based filters for that! |
| 168 | + |
| 169 | +::: |
| 170 | + |
| 171 | +In order to register a "pending tasks count" filter on our ProjectDto, we can do as follows: |
| 172 | + |
| 173 | +```ts |
| 174 | +registerDTOFieldComparison(TestDto, 'pendingTaskCount', 'gt', { |
| 175 | + FilterType: Number, |
| 176 | + GqlType: Int, |
| 177 | + decorators: [IsInt()], |
| 178 | +}); |
| 179 | +``` |
| 180 | + |
| 181 | +Where: |
| 182 | + |
| 183 | +- FilterType is the typescript type of the filter |
| 184 | +- GqlType is the GraphQL type that will be used in the schema |
| 185 | +- decorators represents a list of decorators that will be applied to the filter class at the specific field used for the |
| 186 | + operation, used e.g. for validation purposes |
| 187 | + |
| 188 | +This will add a new operation to the GraphQL `TestDto` input type |
| 189 | + |
| 190 | +```graphql |
| 191 | +input TestPendingTaskCountFilterComparison { |
| 192 | + gt: Int |
| 193 | +} |
| 194 | + |
| 195 | +input TestDtoFilter { |
| 196 | + """ |
| 197 | + ...Other fields defined in TestDTO |
| 198 | + """ |
| 199 | + pendingTaskCount: TestPendingTaskCountFilterComparison |
| 200 | +} |
| 201 | +``` |
| 202 | + |
| 203 | +Now, graphQL will accept the new filter and our persistence layer will be able to receive the key `pendingTaskCount` for all filtering operations related to the "TestDto" DTO. |
0 commit comments