#nullable enable
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;
namespace ErsatzTV.Serialization;
///
/// OpenAPI operation transformer that documents the 400 a model-binding / FluentValidation
/// failure actually returns. ASP.NET Core's [ApiController] convention emits a
/// ValidationProblemDetails (an errors map) for any operation that binds a request body
/// or parameters, but that response was undocumented. This adds a 400 referencing the
/// ValidationProblemDetails schema (declared by
/// ) to every operation that binds something and
/// does not already document a 400. See issues #286/#287.
///
public static class ValidationProblemOperationTransformer
{
public static Task TransformAsync(
OpenApiOperation operation,
OpenApiOperationTransformerContext context,
CancellationToken cancellationToken)
{
bool bindsSomething = operation.RequestBody is not null
|| operation.Parameters is { Count: > 0 };
if (!bindsSomething)
{
return Task.CompletedTask;
}
operation.Responses ??= new OpenApiResponses();
if (operation.Responses.ContainsKey("400"))
{
return Task.CompletedTask;
}
operation.Responses["400"] = new OpenApiResponse
{
Description = "Request validation failed (model binding or FluentValidation).",
Content = new Dictionary
{
["application/json"] = new OpenApiMediaType
{
Schema = new OpenApiSchemaReference(
ApiSecuritySchemeDocumentTransformer.ValidationProblemDetailsSchemaId)
}
}
};
return Task.CompletedTask;
}
}