Skip to content

Commit 679dd12

Browse files
committed
feat(json): ♻️ centralize JSON merge logic
Refactored JSON merging to use a new extension method, improving code organization and reusability. JSON merge operations are now handled via a dedicated method, replacing previous inline implementations.
1 parent 3ca117f commit 679dd12

2 files changed

Lines changed: 26 additions & 26 deletions

File tree

src/EcoFlow.Mqtt.Api/Extensions/JsonExtensions.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,30 @@ public void Sort()
4040
}
4141
}
4242

43+
public void MergeWith(JsonNode nextNode)
44+
{
45+
if (node is not JsonObject previousObject || nextNode is not JsonObject nextObject)
46+
return;
47+
48+
foreach (var nextProperty in nextObject)
49+
{
50+
var previousProperty = previousObject[nextProperty.Key];
51+
52+
if (previousProperty is JsonObject && nextProperty.Value is JsonObject)
53+
{
54+
node.MergeWith(nextProperty.Value);
55+
}
56+
else
57+
{
58+
var clonedNode = nextProperty.Value?.DeepClone();
59+
clonedNode.Sort();
60+
61+
previousObject[nextProperty.Key] = clonedNode;
62+
previousObject.Sort();
63+
}
64+
}
65+
}
66+
4367
public IEnumerable<string> Flatten(string keySeparator = ".", string arrayFormat = "[{0}]")
4468
{
4569
foreach (var flattenedLine in Walk(node, string.Empty))

src/EcoFlow.Mqtt.Api/Services/InternalMqttApi.cs

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,13 @@ private Task OnApplicationMessageReceived(MqttApplicationMessageReceivedEventArg
152152

153153
foreach (var state in _states.Values)
154154
{
155-
if (!state.Devices.TryGetValue(serialNumber, out var device))
155+
if (!state.Devices.TryGetValue(serialNumber, out var deviceNode))
156156
continue;
157157

158158
lock (_states)
159159
{
160160
foreach (var node in nodes)
161-
MergeJsonNodes(device, node);
161+
deviceNode.MergeWith(node);
162162
}
163163

164164
updated = true;
@@ -186,30 +186,6 @@ static bool TryParse(ReadOnlySequence<byte> bytes, [MaybeNullWhen(false)] out st
186186
return false;
187187
}
188188
}
189-
190-
static void MergeJsonNodes(JsonNode previousNode, JsonNode nextNode)
191-
{
192-
if (previousNode is not JsonObject previousObject || nextNode is not JsonObject nextObject)
193-
return;
194-
195-
foreach (var nextProperty in nextObject)
196-
{
197-
var previousProperty = previousObject[nextProperty.Key];
198-
199-
if (previousProperty is JsonObject && nextProperty.Value is JsonObject)
200-
{
201-
MergeJsonNodes(previousProperty, nextProperty.Value);
202-
}
203-
else
204-
{
205-
var clonedNode = nextProperty.Value?.DeepClone();
206-
clonedNode.Sort();
207-
208-
previousObject[nextProperty.Key] = clonedNode;
209-
previousObject.Sort();
210-
}
211-
}
212-
}
213189
}
214190

215191
private record MqttState(IMqttClient Client, ConcurrentDictionary<string, JsonNode> Devices);

0 commit comments

Comments
 (0)