我正在尝试为Ariadne中的联合类型编写查询解析器函数。我该怎么做?
正如我在documentation中所读到的,有一个名为__typename
的字段可帮助我们解析联合类型。但是我的解析器功能没有任何__typename
。
架构
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解析器功能
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
查询我正在尝试
{
unionForCustomTypes {
name
user {
__typename
...on User {
username
firstname
}
}
}
}
当我尝试查询时,我遇到错误
{
"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>"
}
}
}
}
]
}
答案 0 :(得分:0)
对于联合类型,我们不需要任何解析器。我们可以只发送__typename
字段,而返回owner
字段。在我的代码中,我返回了owner
属性的列表,这是错误的。我只需要发送字典。
下面是我在代码中所做的更改,以使其正常运行。
# 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