I am trying to write a query resolver function for union type in Ariadne. How can I accomplish this?
As I have read in the documentation there is a field called __typename
which helps us to resolve the union type. But I am not getting any __typename
to my resolver function.
Schema
type User {
username: String!
firstname: String
email: String
}
type UserDuplicate {
username: String!
firstname: String
email: String
}
union UnionTest = User | UserDuplicate
type UnionForCustomTypes {
user: UnionTest
name: String!
}
type Query {
user: String!
unionForCustomTypes: [UnionForCustomTypes]!
}
Ariadne resolver functions
query = QueryType()
mutation = MutationType()
unionTest = UnionType("UnionTest")
@unionTest.type_resolver
def resolve_union_type(obj, *_):
if obj[0]["__typename"] == "User":
return "User"
if obj[0]["__typename"] == "DuplicateUser":
return "DuplicateUser"
return None
# Query resolvers
@query.field("unionForCustomTypes")
def resolve_union_for_custom_types(_, info):
result = [
{"name": "Manisha Bayya", "user": [{"__typename": "User", "username": "abcd"}]}
]
return result
Query I am trying
{
unionForCustomTypes {
name
user {
__typename
...on User {
username
firstname
}
}
}
}
When I try the query I am getting below error
{
"data": null,
"errors": [
{
"message": "Cannot return null for non-nullable field Query.unionForCustomTypes.",
"locations": [
[
2,
3
]
],
"path": [
"unionForCustomTypes"
],
"extensions": {
"exception": {
"stacktrace": [
"Traceback (most recent call last):",
" File \"/root/manisha/prisma/ariadne_envs/lib/python3.6/site-packages/graphql/execution/execute.py\", line 675, in complete_value_catching_error",
" return_type, field_nodes, info, path, result",
" File \"/root/manisha/prisma/ariadne_envs/lib/python3.6/site-packages/graphql/execution/execute.py\", line 754, in complete_value",
" \"Cannot return null for non-nullable field\"",
"TypeError: Cannot return null for non-nullable field Query.unionForCustomTypes."
],
"context": {
"completed": "None",
"result": "None",
"path": "ResponsePath(...rCustomTypes')",
"info": "GraphQLResolv...f04e9c1fc50>})",
"field_nodes": "[FieldNode at 4:135]",
"return_type": "<GraphQLNonNu...ustomTypes'>>>",
"self": "<graphql.exec...x7f04e75677f0>"
}
}
}
}
]
}
We don't need any resolver for union type. We can just send __typename
field while returning the owner
field. In my code, I am returning list for owner
attribute which is wrong. I have to just send a dictionary.
Below is the change I have done in my code to make it work.
# Deleted resolver for UnionType
@query.field("unionForCustomTypes")
def resolve_union_for_custom_types(_, info):
result = [{"name": "Manisha Bayya", "user": {"__typename": "User", "username": "abcd", "firstname": "pqrs"}}] # <-- Line changed
return result