Skip to content

Commit

Permalink
Use time ms for timespan in redis
Browse files Browse the repository at this point in the history
  • Loading branch information
LucHeart committed Nov 6, 2024
1 parent 5165826 commit d7dd14f
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
2 changes: 2 additions & 0 deletions API/Controller/Admin/GetOnlineDevices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ public sealed class AdminOnlineDeviceResponse
public required DateTimeOffset ConnectedAt { get; init; }

public required string? UserAgent { get; init; }
[JsonConverter(typeof(TimeSpanToMillisecondsConverter))]
public required TimeSpan? Uptime { get; init; }
[JsonConverter(typeof(TimeSpanToMillisecondsConverter))]
public required TimeSpan? Latency { get; init; }
}
}
28 changes: 28 additions & 0 deletions Common/JsonSerialization/TimeSpanToMillisecondsConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace OpenShock.Common.JsonSerialization;

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class TimeSpanToMillisecondsConverter : JsonConverter<TimeSpan>
{
// Converts TimeSpan to JSON
public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
{
// Convert TimeSpan to total milliseconds and write it as a JSON number
writer.WriteNumberValue(value.TotalMilliseconds);
}

// Converts JSON to TimeSpan
public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.Number)
{
throw new JsonException("Expected number representing milliseconds.");
}

// Read the milliseconds as a double and convert to TimeSpan
var milliseconds = reader.GetDouble();
return TimeSpan.FromMilliseconds(milliseconds);
}
}
3 changes: 3 additions & 0 deletions Common/Redis/DeviceOnline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public sealed class DeviceOnline
public required string Gateway { get; set; }
public required DateTimeOffset ConnectedAt { get; set; }
public string? UserAgent { get; set; } = null;

[JsonConverter(typeof(TimeSpanToMillisecondsConverter))]
public TimeSpan? Uptime { get; set; }
[JsonConverter(typeof(TimeSpanToMillisecondsConverter))]
public TimeSpan? Latency { get; set; }
}

0 comments on commit d7dd14f

Please sign in to comment.