Initial
This commit is contained in:
72
LehrerApp.Api/ReadableSnapshotStore.cs
Normal file
72
LehrerApp.Api/ReadableSnapshotStore.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using System.Text.Json;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Server-seitiger Speicher für lesbare Snapshots.
|
||||
/// Eine JSON-Datei pro User – wird bei jedem Export überschrieben.
|
||||
/// Kein Ablauf-Datum – der letzte Stand bleibt bis zum nächsten Export.
|
||||
/// </summary>
|
||||
public class ReadableSnapshotStore
|
||||
{
|
||||
private readonly string _dataPath;
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = false,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
};
|
||||
|
||||
public ReadableSnapshotStore(string dataPath)
|
||||
{
|
||||
_dataPath = Path.Combine(dataPath, "readable");
|
||||
Directory.CreateDirectory(_dataPath);
|
||||
}
|
||||
|
||||
// ── Speichern ─────────────────────────────────────────────────────────────
|
||||
|
||||
public void Store(string userId, ReadableSnapshot snapshot)
|
||||
{
|
||||
var path = SnapshotPath(userId);
|
||||
var json = JsonSerializer.Serialize(snapshot, JsonOptions);
|
||||
File.WriteAllText(path, json);
|
||||
}
|
||||
|
||||
// ── Laden ─────────────────────────────────────────────────────────────────
|
||||
|
||||
public ReadableSnapshot? Load(string userId)
|
||||
{
|
||||
var path = SnapshotPath(userId);
|
||||
if (!File.Exists(path)) return null;
|
||||
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(path);
|
||||
return JsonSerializer.Deserialize<ReadableSnapshot>(json, JsonOptions);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gibt nur die Metadaten zurück – für schnelle Freshness-Prüfung.
|
||||
/// </summary>
|
||||
public SnapshotMeta? LoadMeta(string userId)
|
||||
{
|
||||
var snapshot = Load(userId);
|
||||
return snapshot?.Meta;
|
||||
}
|
||||
|
||||
// ── Hilfsmethoden ─────────────────────────────────────────────────────────
|
||||
|
||||
private string SnapshotPath(string userId)
|
||||
{
|
||||
// Sanitize userId
|
||||
var safe = string.Concat(
|
||||
userId.Where(c => char.IsLetterOrDigit(c) || c == '-' || c == '_'));
|
||||
return Path.Combine(_dataPath, $"{safe}.json");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user