-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateStore.cs
More file actions
35 lines (30 loc) · 1.28 KB
/
StateStore.cs
File metadata and controls
35 lines (30 loc) · 1.28 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
// StateStore.cs
using System.Text.Json;
public static class StateStore
{
static readonly string DataDir = Environment.GetEnvironmentVariable("DATA_DIR") ?? "./data";
static readonly string PathFile = Path.Combine(DataDir, "state.json");
static readonly JsonSerializerOptions J = new() { WriteIndented = true };
public static StateOfWorld Load()
{
if (!File.Exists(PathFile)) return new StateOfWorld();
return JsonSerializer.Deserialize<StateOfWorld>(File.ReadAllText(PathFile), J) ?? new StateOfWorld();
}
public static void Save(StateOfWorld s)
{
Directory.CreateDirectory(DataDir);
File.WriteAllText(PathFile, JsonSerializer.Serialize(s, J));
}
public static void AppendNews(StateOfWorld s, IEnumerable<NewsItem> items, int keepDays = 10)
{
s.CacheNews.AddRange(items);
var cutoff = DateTimeOffset.UtcNow.AddDays(-keepDays);
s.CacheNews = s.CacheNews.Where(n => n.Published >= cutoff).DistinctBy(n => n.Link).ToList();
}
public static void UpsertPrice(StateOfWorld s, PriceItem item)
{
var existing = s.Prices.FirstOrDefault(p => p.Name == item.Name && p.Url == item.Url);
if (existing is null) s.Prices.Add(item);
else existing.Series = item.Series;
}
}