简体   繁体   中英

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 (eg this answer ) this should be possible somehow.

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

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

One solution is to enable nullable reference types and then explicitly mark the list as nullable.

Enable nullable reference types in the .csproj file:

<Nullable>enable</Nullable>
public async Task<List<Foo>?> GetFoos() { ... }

To not change this setting for the whole project (as this likely breaks stuff), the nullable directives can be used to enable this feature just in certain parts of your code:

#nullable enable
public async Task<List<Foo>?> GetFoos() { ... }
#nullable disable

Don't forget to disable it again, otherwise it will also affect any other code below.

While this solves my problem for now, I would still be interested if there is a solution without enabling nullable reference types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM