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?
CodePudding user response:
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.
CodePudding user response:
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