Skip to content

Commit

Permalink
Json Repository Helper supports PUT (update)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dries Verbeke committed Mar 22, 2022
1 parent 4e1a15a commit 5e4cac5
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions Fritz.InstantAPIs/Repositories/Json/JsonRepositoryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public Task<IEnumerable<JsonObject>> 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<int>() == id)
)?.AsObject();
return Task.FromResult(matchedItem);
}
Expand All @@ -35,7 +35,14 @@ public Task<int> 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<int>())
.Select(x => x.GetValueOrDefault())
.Max();

var key = lastKey + 1;
newObj.AsObject().Add("Id", key.ToString());
array.Add(newObj);
context.SaveChanges();
Expand All @@ -45,7 +52,29 @@ public Task<int> 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<int>() == 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<string>()));
}
context.SaveChanges();
}

return Task.CompletedTask;
}

public Task<bool> Delete(HttpRequest request, JsonContext context, string name, int id, CancellationToken cancellationToken)
Expand All @@ -55,7 +84,7 @@ public Task<bool> 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<int>() == id));
if (matchedItem != null)
{
array.RemoveAt(matchedItem.index);
Expand Down

0 comments on commit 5e4cac5

Please sign in to comment.