Skip to content

Commit

Permalink
Improved handling of dictionaries with enum key (#3068)
Browse files Browse the repository at this point in the history
Do not use dictionary keys for empty enums.
  • Loading branch information
flarestudiopl authored Sep 12, 2024
1 parent 1c3b099 commit 09a1282
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -350,16 +350,18 @@ private OpenApiSchema CreateArraySchema(DataContract dataContract, SchemaReposit

private OpenApiSchema CreateDictionarySchema(DataContract dataContract, SchemaRepository schemaRepository)
{
if (dataContract.DictionaryKeys != null)
var knownKeysProperties = dataContract.DictionaryKeys?.ToDictionary(
name => name,
_ => GenerateSchema(dataContract.DictionaryValueType, schemaRepository));

if (knownKeysProperties?.Count > 0)
{
// This is a special case where the set of key values is known (e.g. if the key type is an enum)
return new OpenApiSchema
{
Type = "object",
Properties = dataContract.DictionaryKeys.ToDictionary(
name => name,
name => GenerateSchema(dataContract.DictionaryValueType, schemaRepository)),
AdditionalPropertiesAllowed = false,
Properties = knownKeysProperties,
AdditionalPropertiesAllowed = false
};
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ public void GenerateSchema_DedupsEnumValues_IfEnumTypeHasDuplicateValues()

[Theory]
[InlineData(typeof(IDictionary<string, int>), "integer")]
[InlineData(typeof(IDictionary<EmptyIntEnum, int>), "integer")]
[InlineData(typeof(IReadOnlyDictionary<string, bool>), "boolean")]
[InlineData(typeof(IDictionary), null)]
[InlineData(typeof(ExpandoObject), null)]
Expand Down
6 changes: 5 additions & 1 deletion test/Swashbuckle.AspNetCore.TestSupport/Fixtures/Enums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public enum ShortEnum:short
Value8 = 8,
}

public enum EmptyIntEnum:int
{
}

public enum IntEnum:int
{
Value2 = 2,
Expand All @@ -27,4 +31,4 @@ public enum LongEnum:long
Value4 = 4,
Value8 = 8,
}
}
}

0 comments on commit 09a1282

Please sign in to comment.