diff --git a/Fritz.InstantAPIs/Repositories/Json/JsonRepositoryHelper.cs b/Fritz.InstantAPIs/Repositories/Json/JsonRepositoryHelper.cs index 9531619..f5f7510 100644 --- a/Fritz.InstantAPIs/Repositories/Json/JsonRepositoryHelper.cs +++ b/Fritz.InstantAPIs/Repositories/Json/JsonRepositoryHelper.cs @@ -25,7 +25,7 @@ public Task> Get(HttpRequest request, JsonContext contex var array = context.LoadTable(name); var matchedItem = array.SingleOrDefault(row => row .AsObject() - .Any(o => o.Key.ToLower() == "id" && o.Value.ToString() == id.ToString()) + .Any(o => o.Key.ToLower() == "id" && o.Value?.GetValue() == id) )?.AsObject(); return Task.FromResult(matchedItem); } @@ -35,7 +35,14 @@ public Task Insert(HttpRequest request, JsonContext context, string name, J { var array = context.LoadTable(name); - var key = array.Count + 1; + var lastKey = array + .Select(row => row + .AsObject() + .FirstOrDefault(o => o.Key.ToLower() == "id").Value?.GetValue()) + .Select(x => x.GetValueOrDefault()) + .Max(); + + var key = lastKey + 1; newObj.AsObject().Add("Id", key.ToString()); array.Add(newObj); context.SaveChanges(); @@ -45,7 +52,29 @@ public Task Insert(HttpRequest request, JsonContext context, string name, J public Task Update(HttpRequest request, JsonContext context, string name, int id, JsonObject newObj, CancellationToken cancellationToken) { - throw new NotImplementedException(); + var array = context.LoadTable(name); + var matchedItem = array.SingleOrDefault(row => row + .AsObject() + .Any(o => o.Key.ToLower() == "id" && o.Value.GetValue() == id) + )?.AsObject(); + if (matchedItem != null) + { + var updates = newObj + .GroupJoin(matchedItem, o => o.Key, i => i.Key, (o, i) => new { NewValue = o, OldValue = i.FirstOrDefault() }) + .Where(x => x.NewValue.Key.ToLower() != "id") + .ToList(); + foreach (var newField in updates) + { + if (newField.OldValue.Value != null) + { + matchedItem.Remove(newField.OldValue.Key); + } + matchedItem.Add(newField.NewValue.Key, JsonValue.Create(newField.NewValue.Value.GetValue())); + } + context.SaveChanges(); + } + + return Task.CompletedTask; } public Task Delete(HttpRequest request, JsonContext context, string name, int id, CancellationToken cancellationToken) @@ -55,7 +84,7 @@ public Task Delete(HttpRequest request, JsonContext context, string name, .Select((value, index) => new { value, index }) .SingleOrDefault(row => row.value .AsObject() - .Any(o => o.Key.ToLower() == "id" && o.Value.ToString() == id.ToString())); + .Any(o => o.Key.ToLower() == "id" && o.Value?.GetValue() == id)); if (matchedItem != null) { array.RemoveAt(matchedItem.index);