From 5d407da3b39eb542c448997e4c66bed6afb88260 Mon Sep 17 00:00:00 2001 From: Meghan Date: Thu, 9 May 2024 16:07:59 -0700 Subject: [PATCH] Fix controller --- .../Wordle.Api/Controllers/WordController.cs | 5 ++-- .../Services/WordOfTheDayService.cs | 27 ++++++++++++------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Wordle.Api/Wordle.Api/Controllers/WordController.cs b/Wordle.Api/Wordle.Api/Controllers/WordController.cs index c4254523..e580c9fd 100644 --- a/Wordle.Api/Wordle.Api/Controllers/WordController.cs +++ b/Wordle.Api/Wordle.Api/Controllers/WordController.cs @@ -7,9 +7,10 @@ namespace Wordle.Api.Controllers; public class WordController(WordOfTheDayService wordOfTheDayService) : ControllerBase { [HttpGet("RandomWord")] - public string GetRandomWord() + public async Task GetRandomWord() { - return wordOfTheDayService.GetRandomWord(); + var randomWord = await wordOfTheDayService.GetRandomWord(); + return randomWord.Text; } /// diff --git a/Wordle.Api/Wordle.Api/Services/WordOfTheDayService.cs b/Wordle.Api/Wordle.Api/Services/WordOfTheDayService.cs index e33ef18f..73fed039 100644 --- a/Wordle.Api/Wordle.Api/Services/WordOfTheDayService.cs +++ b/Wordle.Api/Wordle.Api/Services/WordOfTheDayService.cs @@ -15,30 +15,39 @@ public WordOfTheDayService(WordleDbContext db) Db = db; } - public string GetRandomWord() + public async Task GetRandomWord() { + var numberOfWords = await Db.Words.CountAsync(); + Random random = new(); - int index = random.Next(words.Count); - return words[index]; + int randomIndex = random.Next(numberOfWords); + + return await Db.Words.Skip(randomIndex).FirstAsync(); } public async Task GetWordOfTheDay(DateOnly date) { - WordOfTheDay? wordOfTheDay = await Db.WordsOfTheDays.FirstOrDefaultAsync(words => words.Date == date); + WordOfTheDay? wordOfTheDay = await Db.WordsOfTheDays + .Include(wordOfTheDay => wordOfTheDay.Word) + .FirstOrDefaultAsync(wordOfTheDay => wordOfTheDay.Date == date); if (wordOfTheDay is null) { lock (_lock) { - wordOfTheDay = Db.WordsOfTheDays.FirstOrDefault(words => words.Date == date); + wordOfTheDay = Db.WordsOfTheDays + .Include(wordOfTheDay => wordOfTheDay.Word) + .FirstOrDefault(wordOfTheDay => wordOfTheDay.Date == date); + if (wordOfTheDay is null) { + var randomWordTask = GetRandomWord(); + randomWordTask.Wait(); + var randomWord = randomWordTask.Result; + wordOfTheDay = new() { - Word = new Word() - { - Text = GetRandomWord() - }, + Word = randomWord, Date = date };