Skip to content

Improve how we fetch the type for fields with resolvers #396

Open
@patrick91

Description

@patrick91

To define a type for a field we use the approach used by dataclasses:

@strawberry.type
class Q:
    x: int

But we also allow to use strawberry.field to pass a resolver:

def get_x() -> int:
    return 123

@strawberry.type
class Q:
    x: int = strawberry.field(resolver=get_x)

Now, we could allow to omit the type on the field, like this:

def get_x() -> int:
    return 123

@strawberry.type
class Q:
    x = strawberry.field(resolver=get_x)

And we'll use the type coming from the resolver, like we do when using @strawberry.field as a decorator.

This shouldn't be too difficult to achieve, I think the only complexity might be that removing the type might hide the field from the dataclasses fields, thus having to find it manually here: https://github.com/strawberry-graphql/strawberry/blob/master/strawberry/types/type_resolver.py#L224-L235

Currently we also allow to use resolvers without type hints:

def get_x():
    return 123

@strawberry.type
class Q:
    x: int = strawberry.field(resolver=get_x)

I think we should keep this, and maybe just log a warning, which might be useful for debugging.

We also have to consider these two cases where things might be wrong:

  1. Both places are missing type hints
def get_x():
    return 123

@strawberry.type
class Q:
    x = strawberry.field(resolver=get_x)

I'm not 100% what happens in this case, I guess the field isn't shown in the schema currently.

  1. Type hints don't match
def get_x() -> str:
    return '456'

@strawberry.type
class Q:
    x = strawberry.field(resolver=get_x)

Here we need to throw an error and let the user know that something is wrong with the type hints :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions