|
| 1 | +using System.Diagnostics.CodeAnalysis; |
| 2 | +using System.Text.Json; |
| 3 | +using System.Text.Json.Nodes; |
| 4 | +using System.Text.Json.Serialization.Metadata; |
| 5 | + |
| 6 | +namespace Shiny.DocumentDb; |
| 7 | + |
| 8 | +public sealed class JsonPatchDocument<T> where T : class |
| 9 | +{ |
| 10 | + readonly JsonSerializerOptions? options; |
| 11 | + |
| 12 | + public IReadOnlyList<JsonPatchOperation> Operations { get; } |
| 13 | + |
| 14 | + public JsonPatchDocument(IReadOnlyList<JsonPatchOperation> operations, JsonSerializerOptions? options = null) |
| 15 | + { |
| 16 | + Operations = operations; |
| 17 | + this.options = options; |
| 18 | + } |
| 19 | + |
| 20 | + public T ApplyTo(T target, JsonTypeInfo<T> typeInfo) |
| 21 | + { |
| 22 | + var node = JsonSerializer.SerializeToNode(target, typeInfo) |
| 23 | + ?? throw new InvalidOperationException("Serialization produced null."); |
| 24 | + ApplyOperations(node); |
| 25 | + return JsonSerializer.Deserialize(node, typeInfo) |
| 26 | + ?? throw new InvalidOperationException("Deserialization produced null."); |
| 27 | + } |
| 28 | + |
| 29 | + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Reflection path only used when JsonTypeInfo is not provided.")] |
| 30 | + [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "Reflection path only used when JsonTypeInfo is not provided.")] |
| 31 | + public T ApplyTo(T target, JsonSerializerOptions? options = null) |
| 32 | + { |
| 33 | + var opts = options ?? this.options; |
| 34 | + var node = JsonSerializer.SerializeToNode(target, opts) |
| 35 | + ?? throw new InvalidOperationException("Serialization produced null."); |
| 36 | + ApplyOperations(node); |
| 37 | + return JsonSerializer.Deserialize<T>(node, opts!) |
| 38 | + ?? throw new InvalidOperationException("Deserialization produced null."); |
| 39 | + } |
| 40 | + |
| 41 | + void ApplyOperations(JsonNode root) |
| 42 | + { |
| 43 | + foreach (var op in Operations) |
| 44 | + ApplyOp(root, op); |
| 45 | + } |
| 46 | + |
| 47 | + static void ApplyOp(JsonNode root, JsonPatchOperation op) |
| 48 | + { |
| 49 | + var segments = ParsePath(op.Path); |
| 50 | + switch (op.Op) |
| 51 | + { |
| 52 | + case "add": |
| 53 | + case "replace": |
| 54 | + SetValue(root, segments, op.Value); |
| 55 | + break; |
| 56 | + case "remove": |
| 57 | + RemoveValue(root, segments); |
| 58 | + break; |
| 59 | + case "copy": |
| 60 | + var sourceVal = GetValue(root, ParsePath(op.From!)); |
| 61 | + SetValue(root, segments, sourceVal != null |
| 62 | + ? JsonDocument.Parse(sourceVal.ToJsonString()).RootElement.Clone() |
| 63 | + : null); |
| 64 | + break; |
| 65 | + case "move": |
| 66 | + var moveVal = GetValue(root, ParsePath(op.From!)); |
| 67 | + RemoveValue(root, ParsePath(op.From!)); |
| 68 | + SetValue(root, segments, moveVal != null |
| 69 | + ? JsonDocument.Parse(moveVal.ToJsonString()).RootElement.Clone() |
| 70 | + : null); |
| 71 | + break; |
| 72 | + case "test": |
| 73 | + var actual = GetValue(root, segments); |
| 74 | + var expected = op.Value.HasValue |
| 75 | + ? JsonNode.Parse(op.Value.Value.GetRawText()) |
| 76 | + : null; |
| 77 | + if (!JsonNode.DeepEquals(actual, expected)) |
| 78 | + throw new InvalidOperationException($"Test operation failed for path '{op.Path}'."); |
| 79 | + break; |
| 80 | + default: |
| 81 | + throw new NotSupportedException($"Unsupported patch operation: {op.Op}"); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + static string[] ParsePath(string path) |
| 86 | + { |
| 87 | + if (string.IsNullOrEmpty(path) || path == "/") |
| 88 | + return []; |
| 89 | + |
| 90 | + // RFC 6901: skip leading '/' |
| 91 | + return path[1..].Split('/'); |
| 92 | + } |
| 93 | + |
| 94 | + static JsonNode? GetValue(JsonNode root, string[] segments) |
| 95 | + { |
| 96 | + var current = root; |
| 97 | + foreach (var seg in segments) |
| 98 | + { |
| 99 | + if (current is JsonObject obj) |
| 100 | + current = obj[seg]; |
| 101 | + else if (current is JsonArray arr && int.TryParse(seg, out var idx)) |
| 102 | + current = arr[idx]; |
| 103 | + else |
| 104 | + return null; |
| 105 | + } |
| 106 | + return current; |
| 107 | + } |
| 108 | + |
| 109 | + static void SetValue(JsonNode root, string[] segments, JsonElement? value) |
| 110 | + { |
| 111 | + if (segments.Length == 0) |
| 112 | + throw new InvalidOperationException("Cannot set the root node."); |
| 113 | + |
| 114 | + var parent = NavigateToParent(root, segments); |
| 115 | + var key = segments[^1]; |
| 116 | + var nodeValue = value.HasValue ? JsonNode.Parse(value.Value.GetRawText()) : null; |
| 117 | + |
| 118 | + if (parent is JsonObject obj) |
| 119 | + { |
| 120 | + obj[key] = nodeValue; |
| 121 | + } |
| 122 | + else if (parent is JsonArray arr && int.TryParse(key, out var idx)) |
| 123 | + { |
| 124 | + if (idx == arr.Count) |
| 125 | + arr.Add(nodeValue); |
| 126 | + else |
| 127 | + arr[idx] = nodeValue; |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + static void RemoveValue(JsonNode root, string[] segments) |
| 132 | + { |
| 133 | + if (segments.Length == 0) |
| 134 | + throw new InvalidOperationException("Cannot remove the root node."); |
| 135 | + |
| 136 | + var parent = NavigateToParent(root, segments); |
| 137 | + var key = segments[^1]; |
| 138 | + |
| 139 | + if (parent is JsonObject obj) |
| 140 | + obj.Remove(key); |
| 141 | + else if (parent is JsonArray arr && int.TryParse(key, out var idx)) |
| 142 | + arr.RemoveAt(idx); |
| 143 | + } |
| 144 | + |
| 145 | + static JsonNode NavigateToParent(JsonNode root, string[] segments) |
| 146 | + { |
| 147 | + var current = root; |
| 148 | + for (var i = 0; i < segments.Length - 1; i++) |
| 149 | + { |
| 150 | + var seg = segments[i]; |
| 151 | + if (current is JsonObject obj) |
| 152 | + current = obj[seg] ?? throw new InvalidOperationException($"Path segment '{seg}' not found."); |
| 153 | + else if (current is JsonArray arr && int.TryParse(seg, out var idx)) |
| 154 | + current = arr[idx] ?? throw new InvalidOperationException($"Array index '{idx}' not found."); |
| 155 | + else |
| 156 | + throw new InvalidOperationException($"Cannot navigate path segment '{seg}'."); |
| 157 | + } |
| 158 | + return current; |
| 159 | + } |
| 160 | +} |
0 commit comments