graphql-python / graphene-pydantic

Integrate GraphQL with your Pydantic models
Other
229 stars 44 forks source link

How do we indicate that a List is made of non-null elements? #47

Closed CharlesW95 closed 3 years ago

CharlesW95 commented 4 years ago

Right now, when my pydantic model looks like the following:

class MyClassModel(BaseModel):
    myList: List[str]

and my graphene model looks like this:

class MyClassType(PydanticObjectType):
    class Meta:
        model = MyClassModel
        fields = ("myList")

the GraphQL schema output for this field looks like this:

myList: [String]!

This means that introspection in TypeScript interprets each element in the List as a Maybe<String> instead of a String. What can I do here to ensure that the type is myList: [String!]!?

Thanks!

davidkell commented 3 years ago

Just reading the source code, I don't think this is currently possible without manually overriding, i.e.

class MyClassType(PydanticObjectType):
    class Meta:
        model = MyClassModel

    myList = graphene.List(graphene.NonNull(String), required=True)

I haven't tested this, but I think the fix would be here to replace:

        return List(graphene_type)

with

        if not field.sub_fields[0].allow_none:
                graphene_type = graphene.NonNull(graphene_type)
        return List(graphene_type)

i.e. inspecting the nullability of the first subfield

CharlesW95 commented 3 years ago

@daviddaskell Thank you! Only need this in one case so going to use the manual override for now.