el peregrino
el peregrino

Reputation: 791

How to document conditionally required property with Swashbuckle

We have the following request model:

public class SequenceRequest<TPayload>: SequenceRequest
{
    public TPayload Payload { get; set; }
}

The Payload property is conditionally required based on the type of the TPayload.

Is there a way how can I set the Required property of the OpenApiParameter based on that, e.g. using the IOperationFilter?

I can see a lot of information in the OperationFilterContext describing the request, but I am not sure what I need to override.

Could anybody provide an example, please?

Upvotes: 1

Views: 733

Answers (1)

el peregrino
el peregrino

Reputation: 791

Finally, I got a solution for my case using a schema filter.

public class PayloadRequiredSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // from the model definition we know, the type is generic
        // and derived from a non-generic SequenceRequest
        if (context.Type.IsGenericType && context.Type.IsSubclassOf(typeof(SequenceRequest)))
        {
            // from the model we know it has one generic argument
            var argumentType = context.Type.GenericTypeArguments.First();

            // in our case the Payload is not required when it is of the SequencePayload type
            if (argumentType.Equals(typeof(SequencePayload)))
            {
                return;
            }

            // the Payload is required
            // we know the property name
            // however, the list of properties is serialized => the key may change based on the serializer options
            var propertyName = schema.Properties.Single(p => argumentType.Name.Equals(p.Value.Reference?.Id)).Key;
            // mark the property as required
            schema.Required.Add(propertyName);
        }
    }
}

Upvotes: 1

Related Questions