-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisRepository.cs
More file actions
43 lines (34 loc) · 1.27 KB
/
Copy pathRedisRepository.cs
File metadata and controls
43 lines (34 loc) · 1.27 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
using StackExchange.Redis;
using System.Text.Json.Nodes;
namespace PlanApi;
public class RedisRepository : IPlanRepository
{
private readonly IDatabase _db;
public RedisRepository(IConnectionMultiplexer mux)
{
_db = mux.GetDatabase();
}
public Task<bool> ExistsAsync(string objectId) =>
_db.KeyExistsAsync($"plan:{objectId}");
public async Task SaveFlattenedAsync(IReadOnlyDictionary<string, JsonObject> records)
{
var writes = records.Select(kvp => _db.StringSetAsync(kvp.Key, kvp.Value.ToJsonString()));
await Task.WhenAll(writes);
}
public Task<JsonObject?> GetAsync(string objectId) =>
PlanFlattener.AssembleAsync($"plan:{objectId}", ReadRawAsync);
private async Task<string?> ReadRawAsync(string key)
{
var value = await _db.StringGetAsync(key);
return value.HasValue ? value.ToString() : null;
}
public async Task<bool> DeleteAsync(string objectId)
{
var rootKey = $"plan:{objectId}";
var keys = await PlanFlattener.CollectKeysAsync(rootKey, ReadRawAsync);
if (keys.Count == 0) return false;
var redisKeys = keys.Select(k => (RedisKey)k).ToArray();
await _db.KeyDeleteAsync(redisKeys);
return true;
}
}