Search code examples
c#.netgraphqlhotchocolate

How to define a nullable list with non-nullable items in a GraphQL schema using HotChocolate?


I'm using C# 10 but with nullable reference types disabled on .NET 6 and HotChocolate 12.12.0.

My Query.cs has an entry like this:

public async Task<List<Foo>> GetFoos() { ... }

The generated GraphQL schema looks like this: foos: [Foo] (nullable array with nullable Foo-items)

When I add the [GraphQLNonNullType] attribute to the GetFoos() method, the generated GraphQL schema looks like this: foos: [Foo!]! (non-nullable array with non-nullable Foo-items)

What I want my schema to look like is this: foos: [Foo!] (nullable array with non-nullable Foo-items)

From what I've found (e.g. this answer) this should be possible somehow.

Does HotChocolate provide any way to produce a nullable array with non-nullable items in the schema?


Solution

  • Yes, this is possible using Hot Chocolate.

    Using annotation-based approach:

    [GraphQLType(typeof(ListType<NonNullType<ObjectType<Foo>>>))]
    public async Task<List<Foo>> GetFoos() { ... }
    

    Using code-first approach:

    descriptor
        .Field("foos")
        .Type<ListType<NonNullType<ObjectType<Foo>>>>();
    

    https://chillicream.com/docs/hotchocolate/defining-a-schema/non-null/#explicit-nullability