diff --git a/src/ApiService/ApiService/OneFuzzTypes/Model.cs b/src/ApiService/ApiService/OneFuzzTypes/Model.cs index bd0d6a5179..d182a95285 100644 --- a/src/ApiService/ApiService/OneFuzzTypes/Model.cs +++ b/src/ApiService/ApiService/OneFuzzTypes/Model.cs @@ -5,6 +5,7 @@ using Endpoint = System.String; using GroupId = System.Guid; using PrincipalId = System.Guid; +using System.Text.Json; namespace Microsoft.OneFuzz.Service; @@ -393,11 +394,26 @@ Dictionary Tags ) : EntityBase(); +[JsonConverter(typeof(ContainerConverter))] public record Container(string ContainerName) { public string ContainerName { get; } = ContainerName.All(c => char.IsLetterOrDigit(c) || c == '-') ? ContainerName : throw new ArgumentException("Container name must have only numbers, letters or dashes"); } +public class ContainerConverter : JsonConverter +{ + public override Container? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var containerName = reader.GetString(); + return containerName == null ? null : new Container(containerName); + } + + public override void Write(Utf8JsonWriter writer, Container value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ContainerName); + } +} + public record Notification( DateTime? Timestamp, Container Container, diff --git a/src/ApiService/Tests/OrmTest.cs b/src/ApiService/Tests/OrmTest.cs index 5a7033990a..97ba10f262 100644 --- a/src/ApiService/Tests/OrmTest.cs +++ b/src/ApiService/Tests/OrmTest.cs @@ -276,5 +276,41 @@ public void TestEventSerialization2() var actualEvent = converter.ToRecord(te); Assert.Equal(expectedEvent, actualEvent); } + + record Entity3( + [PartitionKey] int Id, + [RowKey] string TheName, + Container Container + ) : EntityBase(); + + [Fact] + public void TestContainerSerialization() + { + var container = new Container("abc-123"); + var expected = new Entity3(123, "abc", container); + var converter = new EntityConverter(); + + var tableEntity = converter.ToTableEntity(expected); + var actual = converter.ToRecord(tableEntity); + + Assert.Equal(expected.Container.ContainerName, actual.Container.ContainerName); + Assert.Equal(expected.Container.ContainerName, tableEntity.GetString("container")); + } + + [Fact] + public void TestContainerSerialization2() + { + var entityJson = +@"{ + ""Id"": 123, + ""TheName"": ""abc"", + ""Container"": ""abc-123"" +}"; + var entity = JsonSerializer.Deserialize(entityJson); + + Assert.Equal(123, entity?.Id); + Assert.Equal("abc", entity?.TheName); + Assert.Equal("abc-123", entity?.Container.ContainerName); + } } -} \ No newline at end of file +}