Remove caching; add previous/next puzzle dates to puzzles

This commit is contained in:
2024-06-29 17:08:34 +02:00
parent e260012e20
commit e54f501f9a
8 changed files with 143 additions and 55 deletions

View File

@@ -0,0 +1,76 @@
using ConnectionsAPI.Database.Entities;
using Microsoft.EntityFrameworkCore;
namespace ConnectionsAPI.Database.Repository
{
public class PuzzleRepository(ConnectionsContext _db)
{
private readonly ConnectionsContext _db = _db;
public async Task<Puzzle?> GetPuzzleByDateAsync(string printDate, bool includeSolutions = true)
{
// query for the puzzle
var query = _db.Puzzles.AsNoTracking();
if (includeSolutions)
{
query = query
.Include(x => x.Categories)
.ThenInclude(x => x.PuzzleCards);
}
var puzzle = await query.FirstOrDefaultAsync(x => x.PrintDate == printDate);
// if not found, we're done here
if (puzzle == null)
{
return null;
}
await EnhancePuzzleWithDatesAsync(puzzle);
return puzzle;
}
public async Task<IEnumerable<Puzzle>> GetAllPuzzlesAsync(bool includeSolutions = true)
{
// query all, ordered by print date
var query = _db.Puzzles
.AsNoTracking();
if (includeSolutions)
{
query = query
.Include(x => x.Categories)
.ThenInclude(x => x.PuzzleCards);
}
var result = (await query.OrderBy(x => x.PrintDate).ToListAsync()) ?? [];
foreach (var puzzle in result)
{
await EnhancePuzzleWithDatesAsync(puzzle);
}
return result;
}
private async Task EnhancePuzzleWithDatesAsync(Puzzle puzzle)
{
string? previousPuzzleDate = await _db.Puzzles.AsNoTracking()
.Where(x => x.PrintDate.CompareTo(puzzle.PrintDate) < 0)
.OrderByDescending(x => x.PrintDate)
.Select(x => x.PrintDate)
.FirstOrDefaultAsync();
string? nextPuzzleDate = await _db.Puzzles.AsNoTracking()
.Where(x => x.PrintDate.CompareTo(puzzle.PrintDate) > 0)
.OrderBy(x => x.PrintDate)
.Select(x => x.PrintDate)
.FirstOrDefaultAsync();
puzzle.PrevPrintDate = previousPuzzleDate;
puzzle.NextPrintDate = nextPuzzleDate;
}
}
}