Support for Enforcing Non-Nullability in Schema for Single Item IQueryable Return Types
Product
Hot Chocolate
Is your feature request related to a problem?
We're using HotChocolate for our GraphQL API in a .NET project, and we have a common pattern where our GraphQL mutation functions return an IQueryable<T>. We're using the UseSingleOrDefault middleware to ensure that the returned IQueryable<T> only contains a single item, but in our schema, we'd like the return type of these mutations to be non-nullable.
We've found that the current middleware implementation results in nullable types in the schema. This doesn't align with our domain requirements because these mutations will always return a value or throw an exception in our scenario. The nullability of the return type in the schema suggests to the client that they might receive a null, which won't be the case.
The solution you'd like
We're looking for a way to maintain the use of IQueryable<T> in our mutation functions but have the corresponding GraphQL type as non-nullable in the schema. Ideally, this could be handled via a middleware similar to UseSingleOrDefault that enforces non-nullability in the schema.
A rough example might look like this:
[HotChocolate.Data.UseSingle] // Hypothetical new middleware enforcing non-nullability
[UseProjection]
public async Task<IQueryable<Payload>> CreateResourceAsync(
DbContext dbContext,
ResourceInput input)
{
...
return dbContext.Resources.AsQueryable();
}
In the GraphQL schema, the mutation's return type should be defined as Payload! and not Payload.
Alternatives
We've considered using the code-first approach to define our schema but prefer to stick with the attribute-based approach. We've also tried creating a custom middleware to handle this, but we struggled to enforce the non-nullability in the schema.