Search code examples
graphqlhotchocolate

How can I prevent HotChocolate from transforming single values into array with single value?


I am using HotChocolate v13 for my .NET 6 API and I am experiencing issues with the default behavior. Here is the type used for my query variables:

public class AssetQueryType : InputObjectType<AssetQuery>
{
    public const string AssetQueryTypeName = "AssetQueryType";
    protected override void Configure(
        IInputObjectTypeDescriptor<AssetQuery> descriptor)
    {
        descriptor.Name(AssetQueryTypeName);
        descriptor.Field(x => x.Markets).Type<ListType<StringType>>();
        descriptor.Field(x => x.Locations).Type<ListType<StringType>>();
        descriptor.Field(x => x.Assets).Type<ListType<StringType>>();
        descriptor.Field(x => x.Categories).Type<ListType<StringType>>();
        descriptor.Field(x => x.Page).Type<NonNullType<IntType>>();
        descriptor.Field(x => x.ItemsPerPage).Type<NonNullType<IntType>>();
        descriptor.Field(x => x.Rules).Type<AssetRuleType>();
    }
}

The problem is that when I send a query variable like this:

{
  "query": {
    "page": 1,
    "itemsPerPage": 100,  
    "markets": "UK",
    "locations": ["12A", "30F"] 
    }
}

I don't get BadRequest error and string value provided for the market is being parsed as an array with a single string. How can I enforce proper query validation? Strict validation is turned on.


Solution

  • It's by design, as specified in GraphQL spec:

    If the value passed as an input to a list type is not a list and not the null value, then the result of input coercion is a list of size one, where the single item value is the result of input coercion for the list’s item type on the provided value (note this may apply recursively for nested lists).

    You can also read this github issue:

    This ends up coming in handy for consumers of your GraphQL API. For example, releaseGroups(type: ALBUM) is nicer than remembering to have to type releaseGroups(type: [ALBUM]), and still allows for releaseGroups(type: [ALBUM, EP]).