strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
https://strawberry.rocks/docs/django
MIT License
415 stars 120 forks source link

Pagination with union types #275

Open MaehMaeh opened 1 year ago

MaehMaeh commented 1 year ago

Is there a possibility to do a pagination with union types?

My implementation currently looks like this (without Unions):

@strawberry_django.type(
    model=models.User, filters=UserFilter, order=UserOrder, pagination=True
)
class UserType:
    id: auto
    name: auto

@strawberry.type
class Queries:

    @gql.django.connection
    async def users(self, info: Info) -> Iterable[UserType]:
        return models.User.objects.all()

This makes the query look like this:

{
  users(first: 5, after: "YXJyYXljb25uZWN0aW9uOjk=") {
    edges {
      node {
        id
        name
      }
    }
    totalCount
  }
}

But my wish would be that the query should be with Unions. So like this:

{
  users(first: 5, after: "YXJyYXljb25uZWN0aW9uOjk=") {
    edges {
      node {
        ... on User {
          id
          name
        }
        ... on PermissionProblem {
          message
        }
      }
    }
    totalCount
  }
}

If I make the query return a union type, like this:

UsersResult = strawberry.union(
    "UsersResult", types=[User, PermissionProblem]
)

@strawberry.type
class Queries:

    @gql.django.connection
    async def users(self, info: Info) -> Iterable[UsersResult]:
        try:
            # This function can throw a `PermissionDenied`
            return models.User.objects.all()
        except PermissionDenied as err:
            return PermissionProblem(message=str(err))

I get the error message 'StrawberryUnion' object has no attribute '_type_definition'

I hope I have been able to formulate my request in a reasonably understandable way. Is there currently such a possibility?

Upvote & Fund

Fund with Polar

bellini666 commented 1 year ago

Hey @MaehMaeh ,

This is actually the same issue as the one described here: https://github.com/strawberry-graphql/strawberry/issues/2893

We still need to find a better way of handling unions for connections when using an iterable resolver, but in the meantime you can try to use the workaround I suggested in that issue