@@ -13,7 +13,8 @@ import Data.Map as Map
1313import Data.Maybe (Maybe(..), fromMaybe)
1414import Data.Newtype (class Newtype, unwrap)
1515import Data.String (trim)
16−import Effect.Aff (Aff, Error, throwError, error)
16+import Data.Variant (Variant, inj)
17+import Effect.Aff (Aff, Error, error, throwError)
1718import GraphQL ((!!>), (!#>), (!>), (.>), (:>), (?>))
1819import GraphQL as GQL
1920import Test.Spec (Spec, describe, it)
@@ -82,6 +83,32 @@ queryType =
8283 !> (\{ on: onArg } _ -> pure $ not onArg)
8384 :> GQL.nullableField "fail" GQL.boolean
8485 !!> (\_ -> throwError $ error "Always fails at runtime.")
86+ :> GQL.field "unionField" exampleUnionType
87+ ?> GQL.arg GQL.string (Proxy :: _ "type")
88+ !> resolveUnion
89+
90+
91+resolveUnion :: { "type" :: String } -> String -> (Either Error) ExampleVariant
92+resolveUnion args _ = case args.type of
93+ "user" -> pure $ inj (Proxy :: _ "user") $ User { id: "user1", name: "Hendrik", age: 25, level: NormalUser }
94+ "test" -> pure $ inj (Proxy :: _ "test") "test"
95+ _ -> throwError $ error "Unknown type"
96+
97+
98+type ExampleVariant = Variant (user :: User, test :: String)
99+
100+
101+exampleUnionType :: GQL.UnionType (Either Error) ExampleVariant
102+exampleUnionType = GQL.union "ExampleUnion" { user: userType, test: testType }
103+
104+
105+testType :: GQL.ObjectType (Either Error) String
106+testType =
107+ GQL.objectType "Test"
108+ .> "A test type"
109+ :> GQL.field "test" GQL.string
110+ !#> const "test"
111+
85112
86113
87114userType :: GQL.ObjectType (Either Error) User
@@ -209,6 +236,22 @@ executionSpec =
209236 res <- GQL.graphql testSchema query (Map.insert "arg" Json.jsonNull Map.empty) Nothing ""
210237 stringify res `shouldEqual` """{"data":{"reflectStringOptional":"default"}}"""
211238
239+ it "returns the right type name on union types" do
240+ testQuery
241+ """{ unionField(type: "user") { __typename } }"""
242+ """{"data":{"unionField":{"__typename":"User"}}}"""
243+ testQuery
244+ """{ unionField(type: "test") { __typename } }"""
245+ """{"data":{"unionField":{"__typename":"Test"}}}"""
246+
247+ it "resolves union type data correctly" do
248+ testQuery
249+ """{ unionField(type: "user") { ... on User { id } } }"""
250+ """{"data":{"unionField":{"id":"user1"}}}"""
251+ testQuery
252+ """{ unionField(type: "test") { ... on Test { test } } }"""
253+ """{"data":{"unionField":{"test":"test"}}}"""
254+
212255
213256introspectionSpec :: Spec Unit
214257introspectionSpec =