From Hotchocolate documentation:
Hot Chocolate has three kinds of middleware. The query middleware which allows to extend or rewrite the processing of a query request, the field middleware which allows to extend or rewrite the processing of field resolvers and the directive middleware which allows basically to add a field middleware to fields that are annotated with a specific directive.
To test the middleware I tried to introduce a new directive that can return the Base64 decoding of the ids decoded by the introduction of the Global Object Identifier.
The process is simple:
public class DecodeBase64DirectiveType : DirectiveType
{
protected override void Configure(IDirectiveTypeDescriptor descriptor)
{
descriptor.Name("decodeBase64");
descriptor.Location(DirectiveLocation.Field);
descriptor.Use(next => async context =>
{
await next.Invoke(context);
if (context.Result is string s)
{
byte[] data = Convert.FromBase64String(s);
context.Result = Encoding.UTF8.GetString(data);
}
});
}
}
Register it
builder.Services.AddDirectiveType<DecodeBase64DirectiveType>()
et voilà. Now it is possible to make queries that decode the single returned field:
query {
authorById(id: "2d2cbbee-5a3a-4102-bc41-04679bfa2968") {
id @decodeBase64
firstName
}
}
the result now is this:
{
"data": {
"authorById": {
"id": "Author\nd2d2cbbee-5a3a-4102-bc41-04679bfa2968",
"firstName": "Faustina"
}
}
}