Skip to content

Commit

Permalink
port domaindrivendev#2825 Generate Enum-Dictionary-Keys (analogous to…
Browse files Browse the repository at this point in the history
… Newtonsoft)
  • Loading branch information
Havunen committed May 5, 2024
1 parent d3608fa commit 59fb631
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,24 @@ public DataContract GetDataContractForType(Type type)

if (IsSupportedDictionary(type, out Type keyType, out Type valueType))
{
IEnumerable<string> keys = null;

if (keyType.IsEnum)
{
// This is a special case where we know the possible key values
var enumValuesAsJson = keyType.GetEnumValues()
.Cast<object>()
.Select(value => JsonConverterFunc(value));

keys = enumValuesAsJson.Any(json => json.StartsWith("\""))
? enumValuesAsJson.Select(json => json.Replace("\"", string.Empty))
: keyType.GetEnumNames();
}

return DataContract.ForDictionary(
underlyingType: type,
valueType: valueType,
keys: null, // STJ doesn't currently support dictionaries with enum key types
keys: keys,
jsonConverter: JsonConverterFunc);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,17 @@ public void UInt128_HaveMinAndMax_DefinedInSchema()
Assert.Equal(true, schema.Nullable);
}

[Fact]
public void GenerateSchema_HonorsEnumDictionaryKeys_StringEnumConverter()
{
var subject = Subject();
var schemaRepository = new SchemaRepository();

var referenceSchema = subject.GenerateSchema(typeof(Dictionary<IntEnum, string>), schemaRepository);

Assert.Equal(typeof(IntEnum).GetEnumNames(), referenceSchema.Properties.Keys);
}

[Theory]
[InlineData(typeof(IntEnum), "integer", "int32", "2", "4", "8")]
[InlineData(typeof(LongEnum), "integer", "int64", "2", "4", "8")]
Expand Down

0 comments on commit 59fb631

Please sign in to comment.