-
Notifications
You must be signed in to change notification settings - Fork 74
ObjectListFilter filter values to target type coercion
#589
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
143d46c
Refactored `ObjectListFilter`: modularized, added type coercion
xperiandri 3964321
Refactor 'ObjectListFilter' to use 'System.Text.Json' coercion
xperiandri ce93746
Updateв schema, add type coercion guide, bug report, tools
xperiandri c61a004
Rebase fix
xperiandri 0e536db
Update filters to use `CurrentCulture` string comparison
xperiandri 2b531ac
Rebase fixes
xperiandri 46e46b3
Removed unnecessary `ObjectListFilterValidationException`
xperiandri 01fb5ee
Added test traits
xperiandri af5eeb2
AI review fixes
xperiandri 47cf92e
Fix ObjectListFilter IN coercion behavior and add converter/no-conver…
xperiandri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
386 changes: 20 additions & 366 deletions
386
src/FSharp.Data.GraphQL.Server.Middleware/ObjectListFilter.fs
Large diffs are not rendered by default.
Oops, something went wrong.
407 changes: 407 additions & 0 deletions
407
src/FSharp.Data.GraphQL.Server.Middleware/ObjectListFilterModule.fs
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
236 changes: 236 additions & 0 deletions
236
src/FSharp.Data.GraphQL.Server.Middleware/TypeCoercion.fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,236 @@ | ||
| namespace FSharp.Data.GraphQL.Server.Middleware | ||
|
|
||
| open System | ||
| open System.Buffers | ||
| open System.Collections.Generic | ||
| open System.Reflection | ||
| open System.Text.Json | ||
| open FSharp.Data.GraphQL | ||
| open FSharp.Data.GraphQL.Extensions | ||
|
|
||
| [<RequireQualifiedAccess>] | ||
| module TypeCoercion = | ||
|
|
||
| /// Case-insensitive instance property lookup. The middleware lowercases field names during | ||
| /// parsing, so we must also ignore casing here. | ||
| let propertyBindFlags = | ||
| BindingFlags.Public | ||
| ||| BindingFlags.Instance | ||
| ||| BindingFlags.IgnoreCase | ||
|
|
||
| // Cached type references | ||
| let private stringType = typeof<string> | ||
|
|
||
| /// <summary> | ||
| /// If <paramref name="t"/> is <c>voption</c>, <c>option</c>, or <c>Skippable</c>, returns the inner type; otherwise <see langword="ValueNone"/>. | ||
| /// </summary> | ||
| let tryUnwrapOption (t : Type) : Type voption = | ||
| if t.IsGenericType then | ||
| let fullName = t.GetGenericTypeDefinition().FullName | ||
| if | ||
| fullName.StartsWith ReflectionHelper.ValueOptionTypeName | ||
| || fullName.StartsWith ReflectionHelper.OptionTypeName | ||
| || fullName.StartsWith ReflectionHelper.SkippableTypeName | ||
| then | ||
| ValueSome (t.GetGenericArguments().[0]) | ||
| else | ||
| ValueNone | ||
| else | ||
| ValueNone | ||
|
|
||
| let unwrapOption (t : Type) : Type = | ||
| tryUnwrapOption t |> ValueOption.defaultValue t | ||
|
|
||
| /// <summary> | ||
| /// If <paramref name="t"/> is a generic collection, returns the element type. Handles both concrete collections (where <c>IEnumerable</c> is an | ||
| /// implemented interface) and properties typed directly as <c>IEnumerable<T></c>. | ||
| /// </summary> | ||
| let tryUnwrapEnumerableElement (t : Type) : Type voption = | ||
| let isEnumerableInterface (i : Type) = | ||
| i.IsGenericType | ||
| && Type.(=) (i.GetGenericTypeDefinition (), typedefof<IEnumerable<_>>) | ||
| if Type.(=) (t, stringType) then | ||
| ValueNone | ||
| elif t.IsArray then | ||
| t.GetElementType () |> ValueOption.ofObj | ||
| elif isEnumerableInterface t then | ||
| ValueSome (t.GetGenericArguments()[0]) | ||
| else | ||
| t.GetInterfaces () | ||
| |> Array.vtryFind isEnumerableInterface | ||
| |> ValueOption.map (fun i -> i.GetGenericArguments()[0]) | ||
|
|
||
| /// <summary> | ||
| /// Suffixes the middleware's parser preserves on <c>FieldFilter.FieldName</c> for scalar operators (e.g. <c>meetingId_eq</c>, <c> | ||
| /// validFrom_gte</c>). They must be stripped before resolving the actual CLR property. | ||
| /// These correspond to the lowercase variants produced after Phase 2 parsing in <c>SchemaDefinitions.parseFieldCondition</c>. Longer suffixes are | ||
| /// listed first to prevent shorter ones (e.g. <c>_gt</c>) from incorrectly matching longer ones (e.g. <c>_gte</c>). | ||
| /// </summary> | ||
| let operatorSuffixes = | ||
| [| | ||
| // String operators (case-insensitive variants) | ||
| FilterSuffixConstants.CI.StartsWithSuffix | ||
| FilterSuffixConstants.CI.EndsWithSuffix | ||
| FilterSuffixConstants.CI.SWSuffix | ||
| FilterSuffixConstants.CI.EWSuffix | ||
| FilterSuffixConstants.CI.ContainsSuffix | ||
| FilterSuffixConstants.CI.EqualsSuffix | ||
| FilterSuffixConstants.CI.EQSuffix | ||
| // String operators (case-sensitive variants) | ||
| FilterSuffixConstants.CS.StartsWithSuffix | ||
| FilterSuffixConstants.CS.EndsWithSuffix | ||
| FilterSuffixConstants.CS.SWSuffix | ||
| FilterSuffixConstants.CS.EWSuffix | ||
| FilterSuffixConstants.CS.ContainsSuffix | ||
| FilterSuffixConstants.CS.EqualsSuffix | ||
| FilterSuffixConstants.CS.EQSuffix | ||
| // Numeric/comparison operators (from root) | ||
| FilterSuffixConstants.GreaterThanOrEqualSuffix | ||
| FilterSuffixConstants.LessThanOrEqualSuffix | ||
| FilterSuffixConstants.GreaterThanSuffix | ||
| FilterSuffixConstants.LessThanSuffix | ||
| FilterSuffixConstants.GTESuffix | ||
| FilterSuffixConstants.LTESuffix | ||
| FilterSuffixConstants.GTSuffix | ||
| FilterSuffixConstants.LTSuffix | ||
| FilterSuffixConstants.InSuffix | ||
| |] | ||
|
|
||
| let stripOperatorSuffix (fieldName : string) : string = | ||
| operatorSuffixes | ||
| |> Array.vtryFind (fun s -> fieldName.EndsWith (s, StringComparison.OrdinalIgnoreCase)) | ||
| |> ValueOption.map (fun s -> fieldName.Substring (0, fieldName.Length - s.Length)) | ||
| |> ValueOption.defaultValue fieldName | ||
|
|
||
| /// <summary> | ||
| /// Writes a boxed GraphQL scalar primitive as a JSON token directly into <paramref name="writer"/>. Strings become JSON strings; numbers and | ||
| /// booleans become raw JSON tokens. Returns <c>true</c> if the value was written; <c>false</c> if the type is unsupported. | ||
| /// </summary> | ||
| let private writeJsonValue (value : obj) (writer : Utf8JsonWriter) : bool = | ||
| match value with | ||
| | :? string as s -> | ||
| writer.WriteStringValue s | ||
| true | ||
| | :? bool as b -> | ||
| writer.WriteBooleanValue b | ||
| true | ||
| | :? int64 as n -> | ||
| writer.WriteNumberValue n | ||
| true | ||
| | :? int as n -> | ||
| writer.WriteNumberValue n | ||
| true | ||
| | :? double as n -> | ||
| writer.WriteNumberValue n | ||
| true | ||
| | :? float32 as n -> | ||
| writer.WriteNumberValue n | ||
| true | ||
| | :? decimal as n -> | ||
| writer.WriteNumberValue n | ||
| true | ||
| | _ -> | ||
| false | ||
|
|
||
| // Suppress nullness warnings for the obj / objnull mixture. | ||
| #nowarn "3261" | ||
| /// <summary> | ||
| /// Tries to coerce a value into <paramref name="targetType"/> using STJ deserialization. Primitives are written directly as JSON bytes via | ||
| /// <see cref="writeJsonValue"/> into an <see cref="ArrayBufferWriter{T}"/>, then deserialized from <c>ReadOnlySpan<byte></c>. | ||
| /// Already-correct values pass through unchanged. No intermediate string or <see cref="JsonDocument"/> is allocated. | ||
| /// </summary> | ||
| let tryCoerceValue (jsonOptions : JsonSerializerOptions voption) (targetType : Type) (value : objnull) : obj voption = | ||
| if isNull value then | ||
| ValueNone | ||
| elif targetType.IsInstanceOfType value then | ||
| ValueSome value | ||
| else | ||
| let buffer = ArrayBufferWriter<byte> 64 | ||
| use writer = new Utf8JsonWriter (buffer) | ||
| if not (writeJsonValue value writer) then | ||
| ValueNone | ||
| else | ||
| writer.Flush () | ||
| try | ||
| let opts = jsonOptions |> ValueOption.defaultValue JsonSerializerOptions.Default | ||
| JsonSerializer.Deserialize (buffer.WrittenSpan, targetType, opts) |> ValueSome | ||
| with _ -> | ||
| ValueNone | ||
|
|
||
| /// <summary> | ||
| /// Coerces an entire <see cref="ObjectListFilter"/> tree recursively by resolving the entities's properties and converting filter values into the | ||
| /// property's CLR type. | ||
| /// </summary> | ||
| let rec coerceFilter (jsonOptions : JsonSerializerOptions voption) (entityType : Type) (filter : ObjectListFilter) : ObjectListFilter = | ||
| match filter with | ||
| | And (l, r) -> And (coerceFilter jsonOptions entityType l, coerceFilter jsonOptions entityType r) | ||
| | Or (l, r) -> Or (coerceFilter jsonOptions entityType l, coerceFilter jsonOptions entityType r) | ||
| | Not f -> Not (coerceFilter jsonOptions entityType f) | ||
| | OfTypes _ -> filter | ||
| | Equals (ff, cmp) -> | ||
| match entityType.GetProperty (stripOperatorSuffix ff.FieldName, propertyBindFlags) with | ||
| | null -> filter | ||
| | prop -> | ||
| let unwrapped = unwrapOption prop.PropertyType | ||
| match tryCoerceValue jsonOptions unwrapped (box ff.Value) with | ||
| | ValueNone -> filter | ||
| | ValueSome coerced -> Equals ({ ff with Value = coerced :?> IComparable }, cmp) | ||
| | GreaterThan ff | ||
| | GreaterThanOrEqual ff | ||
| | LessThan ff | ||
| | LessThanOrEqual ff as originalFilter -> | ||
| match entityType.GetProperty (stripOperatorSuffix ff.FieldName, propertyBindFlags) with | ||
| | null -> filter | ||
| | prop -> | ||
| let unwrapped = unwrapOption prop.PropertyType | ||
| match tryCoerceValue jsonOptions unwrapped (box ff.Value) with | ||
| | ValueNone -> filter | ||
| | ValueSome coerced -> | ||
| let coercedField = { ff with Value = coerced :?> IComparable } | ||
| match originalFilter with | ||
| | GreaterThan _ -> GreaterThan coercedField | ||
| | GreaterThanOrEqual _ -> GreaterThanOrEqual coercedField | ||
| | LessThan _ -> LessThan coercedField | ||
| | LessThanOrEqual _ -> LessThanOrEqual coercedField | ||
| | _ -> filter | ||
|
xperiandri marked this conversation as resolved.
|
||
| | In ff -> | ||
| match entityType.GetProperty (stripOperatorSuffix ff.FieldName, propertyBindFlags) with | ||
| | null -> filter | ||
| | prop -> | ||
| let unwrapped = unwrapOption prop.PropertyType | ||
| let coercedList = ff.Value |> List.vchoose (tryCoerceValue jsonOptions unwrapped) | ||
| In { ff with Value = coercedList } | ||
|
xperiandri marked this conversation as resolved.
Outdated
|
||
| | StartsWith (ff, cmp) | ||
| | EndsWith (ff, cmp) as originalFilter -> | ||
| match entityType.GetProperty (stripOperatorSuffix ff.FieldName, propertyBindFlags) with | ||
| | null -> filter | ||
| | _ -> | ||
| match tryCoerceValue jsonOptions stringType (box ff.Value) with | ||
| | ValueNone -> filter | ||
| | ValueSome coerced -> | ||
| let coercedField = { ff with Value = coerced :?> string } | ||
| match originalFilter with | ||
| | StartsWith (_, cmp) -> StartsWith (coercedField, cmp) | ||
| | EndsWith (_, cmp) -> EndsWith (coercedField, cmp) | ||
| | _ -> filter | ||
| | Contains (ff, cmp) -> | ||
| match entityType.GetProperty (stripOperatorSuffix ff.FieldName, propertyBindFlags) with | ||
| | null -> filter | ||
| | prop -> | ||
| let unwrapped = unwrapOption prop.PropertyType | ||
| let coercionTarget = | ||
| match tryUnwrapEnumerableElement unwrapped with | ||
| | ValueSome elementType -> elementType | ||
| | ValueNone -> stringType | ||
| match tryCoerceValue jsonOptions coercionTarget (box ff.Value) with | ||
| | ValueNone -> filter | ||
| | ValueSome coerced -> Contains ({ ff with Value = coerced :?> IComparable }, cmp) | ||
|
xperiandri marked this conversation as resolved.
Outdated
|
||
| | FilterField ff -> | ||
| match entityType.GetProperty (ff.FieldName, propertyBindFlags) with | ||
| | null -> filter | ||
| | prop -> | ||
| let unwrapped = unwrapOption prop.PropertyType | ||
| let nestedType = | ||
| tryUnwrapEnumerableElement unwrapped | ||
| |> ValueOption.defaultValue unwrapped | ||
| FilterField { FieldName = ff.FieldName; Value = coerceFilter jsonOptions nestedType ff.Value } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 3 additions & 1 deletion
4
...ests/ObjectListFilterLinqGenerateTests.fs → ...lter/ObjectListFilterLinqGenerateTests.fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 3 additions & 1 deletion
4
...raphQL.Tests/ObjectListFilterLinqTests.fs → ...ctListFilter/ObjectListFilterLinqTests.fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.