-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEntityCrudModule.cs
More file actions
76 lines (68 loc) · 2.32 KB
/
Copy pathEntityCrudModule.cs
File metadata and controls
76 lines (68 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using Repl;
public sealed class EntityCrudModule<TEntity> : IReplModule
where TEntity : IEntity
{
public void Map(IReplMap map)
{
var name = TEntity.EntityName;
// Top-level collection commands.
map.Map(
"list",
([FromServices] IEntityStore<TEntity> store, [FromServices] IEntityCrudAdapter<TEntity> adapter) =>
store.List().Select(adapter.ToView).ToArray())
.WithDescription($"List all {name}s");
map.Map(
"add {label}",
(string label, [FromServices] IEntityStore<TEntity> store, [FromServices] IEntityCrudAdapter<TEntity> adapter) =>
{
var id = store.NextId();
var entity = adapter.Create(id, label);
store.Save(id, entity);
return Results.Success($"{name} '{id}' added.", adapter.ToView(entity));
})
.WithDescription($"Add a {name}");
// Scoped commands for one selected entity id.
map.Context(
"{id}",
scope =>
{
scope.Map(
"show",
(string id, [FromServices] IEntityStore<TEntity> store, [FromServices] IEntityCrudAdapter<TEntity> adapter) =>
{
var entity = store.Get(id);
return (object)(entity is null
? Results.NotFound($"{name} '{id}' not found.")
: adapter.ToView(entity));
})
.WithDescription($"Show one {name} by id");
scope.Map(
"update {label}",
(string id, string label, [FromServices] IEntityStore<TEntity> store, [FromServices] IEntityCrudAdapter<TEntity> adapter) =>
{
var entity = store.Get(id);
if (entity is null)
{
return Results.NotFound($"{name} '{id}' not found.");
}
var updated = adapter.UpdateFromLabel(entity, label);
store.Save(id, updated);
return Results.Success($"{name} '{id}' updated.", adapter.ToView(updated));
})
.WithDescription($"Update one {name} by id");
scope.Map(
"remove",
(string id, [FromServices] IEntityStore<TEntity> store, [FromServices] IEntityCrudAdapter<TEntity> adapter) =>
{
if (!store.Remove(id))
{
return (object)Results.NotFound($"{name} '{id}' not found.");
}
return (object)Results.NavigateUp(Results.Success($"{name} '{id}' removed."));
})
.WithDescription($"Remove one {name} by id");
},
// Prevent entering the scoped context when id does not exist.
validation: (string id, IEntityStore<TEntity> store) => store.Get(id) is not null);
}
}