losowanie z kategoria

This commit is contained in:
2025-07-21 11:49:01 +02:00
parent d09d8f85e3
commit a8a82df6ed

View File

@@ -186,16 +186,30 @@ public class QuotesController : ControllerBase
[AllowAnonymous]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetRandomQuote()
[ProducesResponseType(204)]
public async Task<IActionResult> GetRandomQuote([FromQuery] int? category_id = null)
{
var totalQuotes = await _db.Quotes.CountAsync();
IQueryable<Quote> query = _db.Quotes.Include(q => q.QuoteCategories!).ThenInclude(qc => qc.Category);
if (category_id.HasValue)
{
query = query.Where(q => q.QuoteCategories!.Any(qc => qc.CategoryId == category_id.Value));
}
var totalQuotes = await query.CountAsync();
if (totalQuotes == 0)
{
if (category_id.HasValue)
return NoContent(); // Brak cytatów w wybranej kategorii
else
return NotFound(new ErrorDTO { Status = "error", Error_msg = "No quotes to choose from" });
}
var random = new Random();
var skip = random.Next(0, totalQuotes);
var quote = await _db.Quotes
var quote = await query
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Skip(skip)