0

我正在尝试为 Ariadne 中的联合类型编写查询解析器函数。我怎样才能做到这一点?

正如我在文档中所读到的,有一个名为的字段__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>"
          }
        }
      }
    }
  ]
}
4

1 回答 1

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
于 2019-07-16T14:33:38.013 回答