Skip to content

Commit 878a90a

Browse files
committed
Implemented sample of filtering union cases by type
1 parent ee4c17f commit 878a90a

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

samples/star-wars-api/Schema.fs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
namespace FSharp.Data.GraphQL.Samples.StarWarsApi
22

3+
open System.Linq
34
open System.Text.Json.Serialization
5+
open Microsoft.FSharp.Reflection
46
open FSharp.Data.GraphQL
57
open FSharp.Data.GraphQL.Types
68
open FSharp.Data.GraphQL.Server.Relay
@@ -292,7 +294,27 @@ module Schema =
292294
Define.Field ("hero", Nullable HumanType, "Gets human hero", inputs, fun ctx _ -> getHuman (ctx.Arg ("id")))
293295
Define.Field ("droid", Nullable DroidType, "Gets droid", inputs, (fun ctx _ -> getDroid (ctx.Arg ("id"))))
294296
Define.Field ("planet", Nullable PlanetType, "Gets planet", inputs, fun ctx _ -> getPlanet (ctx.Arg ("id")))
295-
Define.Field ("characters", ListOf CharacterType, "Gets characters", (fun _ _ -> characters))
297+
// Define discriminator expression for filtering
298+
let typeFilterOptions =
299+
let getUnionCaseName (c : Character) =
300+
match FSharpValue.GetUnionFields (c, typeof<Character>) with
301+
| case, _ -> case.Name
302+
ObjectListFilterLinqOptions<Character, string> ((fun c -> getUnionCaseName c), _.Name)
303+
// The default to compare is the full type name
304+
//ObjectListFilterLinqOptions<Character, string> (getDiscriminator = _.GetType().FullName)
305+
Define.Field (
306+
"characters",
307+
ListOf CharacterType,
308+
"Gets characters",
309+
(fun ctx _ ->
310+
let filter =
311+
match ctx.ExecutionInfo.Kind with
312+
| ResolveCollection element -> element.ResolveAbstractionFilter ctx.Schema.TypeMap
313+
| _ -> invalidOp "Invalid execution info kind"
314+
characters.AsQueryable ()
315+
// Apply filter if less then all union cases are requested
316+
|> ValueOption.foldBack (fun f q -> q.Apply (f, typeFilterOptions)) filter)
317+
)
296318
]
297319
)
298320

0 commit comments

Comments
 (0)