Skip to content

Commit

Permalink
Add DateTimeOffset converter to handle UTC serialization (#661)
Browse files Browse the repository at this point in the history
  • Loading branch information
mtmk authored Oct 22, 2024
1 parent 2bbfe40 commit fbc8a67
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/NATS.Client.JetStream/Models/StreamSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public record StreamSource
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("opt_start_time")]
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
[System.Text.Json.Serialization.JsonConverter(typeof(NatsJSJsonDateTimeOffsetConverter))]
public DateTimeOffset OptStartTime { get; set; }

/// <summary>
Expand Down
22 changes: 22 additions & 0 deletions src/NATS.Client.JetStream/NatsJSJsonSerializer.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using NATS.Client.Core;
Expand Down Expand Up @@ -393,3 +394,24 @@ public override void Write(Utf8JsonWriter writer, TimeSpan? value, JsonSerialize
}
}
}

internal class NatsJSJsonDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
{
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return default;
}

return reader.GetDateTimeOffset();
}

public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
{
// Write the date time in the format e.g. "2024-01-01T00:00:00Z"
// instead of the default DateTimeOffset format e.g. "2024-01-01T00:00:00+00:00"
// which is confusing the server.
writer.WriteStringValue(value.UtcDateTime);
}
}
15 changes: 15 additions & 0 deletions tests/NATS.Client.JetStream.Tests/TimeSpanJsonTests.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
using System.Buffers;
using System.Text;
using System.Text.Json;
using NATS.Client.JetStream.Internal;
using NATS.Client.JetStream.Models;

namespace NATS.Client.JetStream.Tests;

public class TimeSpanJsonTests
{
[Fact]
public void NatsJSJsonDateTimeOffsetConverter_serialize_UTC_offset_as_Z()
{
var streamSource = new StreamSource
{
Name = "events",
OptStartTime = DateTimeOffset.Parse("2024-01-01T00:00:00+00:00"),
};

var json = JsonSerializer.Serialize(streamSource, NatsJSJsonSerializerContext.Default.StreamSource);

Assert.Equal("""{"name":"events","opt_start_time":"2024-01-01T00:00:00Z"}""", json);
}

[Theory]
[InlineData("00:00:00.001", "\"ack_wait\":1000000\\b")]
[InlineData("00:00:01.000", "\"ack_wait\":1000000000\\b")]
Expand Down

0 comments on commit fbc8a67

Please sign in to comment.