Created
August 30, 2018 10:57
-
-
Save Vivelin/705e36c28ccd0db1fa515461e18ee84f to your computer and use it in GitHub Desktop.
A Swagger `ISchemaFilter` that removes duplicate properties in `allOf` schemas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Represents a Swagger filter that removes duplicate properties in 'allOf' | |
/// schema definitions. | |
/// </summary> | |
public class DuplicatePropertySchemaFilter : ISchemaFilter | |
{ | |
private const string DefinitionsRefPrefix = "#/definitions/"; | |
/// <summary> | |
/// Removes duplicate properties from the specified schema. | |
/// </summary> | |
/// <param name="schema">A schema to apply to the filter to.</param> | |
/// <param name="context"> | |
/// A <see cref="SchemaFilterContext"/> that provides context for the | |
/// filter operation. | |
/// </param> | |
public void Apply(Schema schema, SchemaFilterContext context) | |
{ | |
if (schema.AllOf != null) | |
{ | |
var knownProperties = new HashSet<string>(); | |
foreach (var subSchema in schema.AllOf.Select(x => ResolveSchema(x, context.SchemaRegistry))) | |
{ | |
subSchema.Properties = RemoveDuplicateProperties(subSchema, knownProperties); | |
} | |
} | |
} | |
private static Dictionary<string, Schema> RemoveDuplicateProperties(Schema schema, ISet<string> knownProperties) | |
{ | |
var uniqueProperties = new Dictionary<string, Schema>(schema.Properties); | |
foreach (var property in schema.Properties) | |
{ | |
var isNew = knownProperties.Add(property.Key); | |
if (!isNew) | |
{ | |
uniqueProperties.Remove(property.Key); | |
} | |
} | |
return uniqueProperties; | |
} | |
private static Schema ResolveSchema(Schema schema, ISchemaRegistry registry) | |
{ | |
if (string.IsNullOrEmpty(schema.Ref)) | |
return schema; | |
if (!schema.Ref.StartsWith(DefinitionsRefPrefix)) | |
throw new ArgumentException($"The schema reference '{schema.Ref}' is not valid.", nameof(schema)); | |
var name = schema.Ref.Substring(DefinitionsRefPrefix.Length); | |
return registry.Definitions[name]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment