strawberry-graphql / strawberry

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

Strawberry support for Beanie documents (or overriding unknown types) #2098

Open deepmax opened 1 year ago

deepmax commented 1 year ago

Provide support for Beanie or a way to override fields which is unexpected from Strawberry.

Feature Request Type

Description

I am trying to use FastAPI, Strawberry and Beanie to make a service. To establish models using Beanie I defined a class as below

class Book(Document):
    token: Indexed(str, unique=True)
    name: str

    class Settings:
        name = "book"

Beanie is using pydantic's BaseModel as base class for Document and according to Strawberry docs (which is experimental), I tried to do something like this:

@strawberry.experimental.pydantic.type(model=Book, all_fields=True)
class BookType:
    pass

@strawberry.type
class Query:
    @strawberry.field
    async book (self, token: str) -> BookType:
        p = await Book.find_one(Book.token == token)
        return BookType.from_pydantic(p)

Of course it makes an error:

TypeError: BookType fields cannot be resolved. Unexpected type '<class 'beanie.odm.fields.Indexed..NewType'>'

To make it working I can remove all_fields=True and change the class to this:

@strawberry.experimental.pydantic.type(model=Book)
class BookType:
    token: str
    name: strawberry.auto

However the problem is, I have to repeat field name and token both in Book and BookType. In my real application the fields are more than this.


It would be nice if Strawberry was able to work with Beanie Document which has some field types like Indexed or PydanticObjectId.

Another approach which I think is suitable, is the ability to use all_fields=True and also override some fields:

@strawberry.experimental.pydantic.type(model=Book, all_fields=True)
class BookType:
    token: str  # token type is being overridden  to str

Upvote & Fund

Fund with Polar

AiurQIAN commented 1 week ago

Exactly the same problem, any progress?