Rahadian Panji
Rahadian Panji

Reputation: 113

GraphQL Query to return non-iterable

I'm using strawberry-graphql in python, and have a query that returns a list of User

@strawberry.type
class User:
    email: str
    name: str

def get_user():
    items = get_from_database()
    return items

@strawberry.type
class Query:
    all_user: List[User] = strawberry.field(resolver=get_user)

schema = strawberry.Schema(Query)

It works fine, but I want some additional attributes like total_item:

def get_user():
    items = get_from_database()
    return {
        'items': items
        'total_item': len(items)
    }

In above code, Strawberry converts the dict to a string, so It didn't work. I tried to create schemas:

@strawberry.type
class User:
    email: str
    name: str

@strawberry.type
class GetUserResult:
    items: List[User]
    item_count: int

def get_user():
    items = get_from_database()
    return GetUserResult(
        items = items
        item_count = len(items)
    )

But it says a query must return an iterable (Expected Iterable, but did not find one for field 'Query.allUser'.).

Is there any way around?

Upvotes: 1

Views: 702

Answers (1)

patrick
patrick

Reputation: 6860

Here's the fixed example:

from typing import List
import strawberry

@strawberry.type
class User:
    email: str
    name: str

def get_user():
    items = [User(email="email", name="Pat")]
    return GetUserResult(
        items=items,
        item_count=len(items)
    )

@strawberry.type
class User:
    email: str
    name: str

@strawberry.type
class GetUserResult:
    items: List[User]
    item_count: int

@strawberry.type
class Query:
    all_user: GetUserResult = strawberry.field(resolver=get_user)

schema = strawberry.Schema(Query)

you can test here too.

The issue was that in the second snippet you defined:

def get_user():
    items = get_from_database()
    return GetUserResult(
        items = items
        item_count = len(items)
    )

but the query was still expecting a List of users

@strawberry.type
class Query:
    all_user: List[User] = strawberry.field(resolver=get_user)

Upvotes: 2

Related Questions