Skip to content

Commit

Permalink
Fix controller
Browse files Browse the repository at this point in the history
  • Loading branch information
meghanmae committed May 9, 2024
1 parent a58727b commit 5d407da
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
5 changes: 3 additions & 2 deletions Wordle.Api/Wordle.Api/Controllers/WordController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ namespace Wordle.Api.Controllers;
public class WordController(WordOfTheDayService wordOfTheDayService) : ControllerBase
{
[HttpGet("RandomWord")]
public string GetRandomWord()
public async Task<string> GetRandomWord()
{
return wordOfTheDayService.GetRandomWord();
var randomWord = await wordOfTheDayService.GetRandomWord();
return randomWord.Text;
}

/// <summary>
Expand Down
27 changes: 18 additions & 9 deletions Wordle.Api/Wordle.Api/Services/WordOfTheDayService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,39 @@ public WordOfTheDayService(WordleDbContext db)
Db = db;
}

public string GetRandomWord()
public async Task<Word> 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<string> 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
};

Expand Down

0 comments on commit 5d407da

Please sign in to comment.