| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using TicTacToeApp.API.Data; |
| | | 3 | | using TicTacToeApp.API.Entity; |
| | | 4 | | using TicTacToeApp.API.Exceptions; |
| | | 5 | | using TicTacToeApp.API.Interfaces; |
| | | 6 | | using TicTacToeApp.API.Services; |
| | | 7 | | |
| | | 8 | | namespace TicTacToeApp.API.Repositories; |
| | | 9 | | |
| | 2 | 10 | | public sealed class GameAsyncRepository(TicTacToeContext db, ILogger<GameAsyncRepository> log) : IGameAsyncRepository |
| | | 11 | | { |
| | | 12 | | public async Task<Game> FindGameByGuidAsync(Guid id, CancellationToken ct) |
| | | 13 | | { |
| | | 14 | | const string errorMessage = "Нет такой игры"; |
| | 0 | 15 | | var game = await db.Games.FirstOrDefaultAsync(g => g.Id == id, ct); |
| | 0 | 16 | | log.LogError(errorMessage); |
| | 0 | 17 | | return game ?? throw new NotFoundException(errorMessage); |
| | 0 | 18 | | } |
| | | 19 | | |
| | | 20 | | public async Task<IEnumerable<Game>> GetGamesAsync(CancellationToken ct) |
| | | 21 | | { |
| | 1 | 22 | | log.LogInformation("Все игры получены!"); |
| | 1 | 23 | | return await db.Games.AsNoTracking().ToListAsync(ct); |
| | 1 | 24 | | } |
| | | 25 | | |
| | | 26 | | public async Task<Game> CreateGameAsync(int size, CancellationToken ct) |
| | | 27 | | { |
| | 0 | 28 | | if (size < 3) throw new ArgumentException("Поле для игры должно быть минимум 3 на 3"); |
| | | 29 | | |
| | 0 | 30 | | var game = new Game() |
| | 0 | 31 | | { |
| | 0 | 32 | | Board = GameService.CreateEmptyBoard(size) |
| | 0 | 33 | | }; |
| | 0 | 34 | | await db.Games.AddAsync(game, ct); |
| | 0 | 35 | | await db.SaveChangesAsync(ct); |
| | 0 | 36 | | log.LogInformation($"Создана игра {game.Id}"); |
| | 0 | 37 | | return game; |
| | 0 | 38 | | } |
| | | 39 | | |
| | | 40 | | public async Task<bool> UpdateGameAsync(Game game, CancellationToken ct) |
| | | 41 | | { |
| | 0 | 42 | | db.Games.Update(game); |
| | 0 | 43 | | log.LogInformation($"Создана игра {game.Id}"); |
| | 0 | 44 | | return await db.SaveChangesAsync(ct) > 0; |
| | 0 | 45 | | } |
| | | 46 | | |
| | | 47 | | } |