Files
LehrerApp/LehrerApp.Api/ReadableSnapshotStore.cs
2026-03-29 23:47:31 +02:00

73 lines
2.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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");
}
}