strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
3.92k stars 516 forks source link

No way to resolve type of non-strawberry types returned for an interface #1405

Closed AlecRosenbaum closed 1 month ago

AlecRosenbaum commented 2 years ago

This comment is correct: https://github.com/strawberry-graphql/strawberry/blob/feb6edee0df8cac3aeb663f67a169035a0271f40/strawberry/schema/schema_converter.py#L235-L244

It's correctly reflected in the docs, but still does pose a pretty bad limitation for implementations that resolve to non-strawberry types.

The following test fails (using a similar example to https://github.com/strawberry-graphql/strawberry/pull/1150):

def test_interface_type_resolution():
    @strawberry.interface
    class Node:
        id: int

    @strawberry.type
    class Anime(Node):
        name: str

    @dataclass
    class AnimeORM:
        id: int
        name: str

    @strawberry.type
    class Query:
        @strawberry.field
        def node(self) -> Node:
            return AnimeORM(id=1, name="One Piece")  # type: ignore

    schema = strawberry.Schema(query=Query)

    query = "{ node { __typename, id } }"
    result = schema.execute_sync(query)

    assert not result.errors
    assert result.data == {"node": {"__typename": "Anime", "id": 1}}
    # errors with: "type object 'AnimeORM' has no attribute '_type_definition'"

In graphene, the converter allows you to define is_type_of classmethods on concrete types or a resolve_type classmethod on the interface. I think the equivalent within strawberry would be to optionally include is_type_of here, and to gracefully fail type resolution for non-strawberry objects (by returning None) within resolve_type.

Upvote & Fund

Fund with Polar

AlecRosenbaum commented 2 years ago

I was wrong about the graceful failure on resolve_type. graphene doesn't provide a resolve_type function by default. It seem that resolve_type takes precedence over is_type_of if it's present, regardless of what it returns.

If I understand correctly, it seems that graphene forces the presence of a user-defined is_type_of function on implementing types, a resolve_type function on the interface, or will generate an is_type_of function for you based on a list of types provided within the metadata (still explicit / opt-in).

Should strawberry require explicit type resolution for duck-typed objects?

AlecRosenbaum commented 2 years ago

Not sure why this closed...

pheki commented 1 month ago

I think this was fixed by https://github.com/strawberry-graphql/strawberry/pull/1406 (at least that was intended to fix this)