/
evsyukov.s
/
test
Обзор
Документация
Войти
/
evsyukov.s
/
test
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/DicePoker.Core/Data/Repositories/JsonFileGameRepository.cs
87 строк
3 KB
evsyukov.s
Финальная оптимизация перед релизом
15 дек 2025, 11:41
15 дек 2025, 11:41
0d74604
Код
Авторство
О чём код?
using System.Text.Json; using System.Text.Json.Serialization; using DicePoker.Core.Data.Abstractions; using DicePoker.Core.Game; namespace DicePoker.Core.Data.Repositories; /// <summary> /// Реализация репозитория игры на основе JSON файлов /// </summary> public sealed class JsonFileGameRepository : IGameRepository { private readonly string _basePath; private readonly JsonSerializerOptions _jsonOptions; public JsonFileGameRepository(string basePath) { _basePath = basePath ?? throw new ArgumentNullException(nameof(basePath)); _jsonOptions = new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; } public async Task SaveAsync(GameSnapshot snapshot, string key) { if (snapshot == null) throw new ArgumentNullException(nameof(snapshot)); if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Key cannot be empty", nameof(key)); var filePath = GetFilePath(key); EnsureDirectoryExists(filePath); var json = JsonSerializer.Serialize(snapshot, _jsonOptions); await File.WriteAllTextAsync(filePath, json); } public async Task<GameSnapshot?> LoadAsync(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Key cannot be empty", nameof(key)); var filePath = GetFilePath(key); if (!File.Exists(filePath)) return null; var json = await File.ReadAllTextAsync(filePath); return JsonSerializer.Deserialize<GameSnapshot>(json, _jsonOptions); } public Task<bool> ExistsAsync(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Key cannot be empty", nameof(key)); var filePath = GetFilePath(key); return Task.FromResult(File.Exists(filePath)); } public Task DeleteAsync(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Key cannot be empty", nameof(key)); var filePath = GetFilePath(key); if (File.Exists(filePath)) File.Delete(filePath); return Task.CompletedTask; } private string GetFilePath(string key) { // Безопасное имя файла var safeFileName = string.Concat(key.Split(Path.GetInvalidFileNameChars())); if (!safeFileName.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) safeFileName += ".json"; return Path.Combine(_basePath, safeFileName); } private void EnsureDirectoryExists(string filePath) { var directory = Path.GetDirectoryName(filePath); if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } }