Because of our business model we have a "wrapper" type that is implemented as a struct. The type can either hold some data or be "empty". When the struct holds some data, we want to send it as a string but when it is empty the value of the field should be null. This is pretty easy to do (just define a new scalar type) but when the value is null HotChocolate throws an exception because a field that has a struct as the type cannot be null.
I don't want to annotate every instance of the struct so I am looking at a generic way to modify the schema while it is being discovered. It seems that using a TypeInterceptor
is the right thing to do but the documentation of that part of the API is almost non-existent.
Any idea?
Yes this is correct. You can use a type interceptor to rewrite the schema. Override the method OnBeforeRegisterDependencies. There you have access to the field and the definitions.
You can then rewrite the nullability of the type.
Something like this could work:
public class MakeTypeNullableInterceptor<T> : TypeInterceptor
{
public override void OnBeforeRegisterDependencies(
ITypeDiscoveryContext discoveryContext,
DefinitionBase? definition,
IDictionary<string, object?> contextData)
{
if (definition is ObjectTypeDefinition { Fields: var fields })
{
foreach (var field in fields)
{
if (field.Type is not ExtendedTypeReference { Type: var extendedType } typeRef)
{
continue;
}
int position;
for (position = 0; extendedType.ElementType is { } elementType; position++)
{
extendedType = elementType;
}
if (extendedType.Source == typeof(T) && !extendedType.IsNullable)
{
var typeInspector = discoveryContext.TypeInspector;
var nullability = typeInspector.CollectNullability(typeRef.Type);
nullability[position] = true;
field.Type = typeRef
.WithType(typeInspector.ChangeNullability(typeRef.Type, nullability));
}
}
}
}
}