losowanie z kategoria

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

View File

@@ -185,46 +185,60 @@ public class QuotesController : ControllerBase
[HttpGet("random")]
[AllowAnonymous]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetRandomQuote()
{
var totalQuotes = await _db.Quotes.CountAsync();
if (totalQuotes == 0)
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
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Skip(skip)
.Take(1)
.FirstOrDefaultAsync();
if (quote == null)
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Unknown error - couldn't get quote" });
Image? image = null;
if (quote.ImageId != 0)
{
image = await _db.Images.FirstOrDefaultAsync(i => i.Id == quote.ImageId);
}
var dto = new QuoteShortDTO
{
Id = quote.Id,
Text = quote.Text,
Author = quote.Author,
ImageUrl = image?.Url,
Categories = quote.QuoteCategories?
.Select(qc => qc.Category?.Name ?? "")
.Where(name => !string.IsNullOrEmpty(name))
.ToList() ?? new List<string>()
};
return Ok(dto);
[ProducesResponseType(typeof(ErrorDTO), 404)]
[ProducesResponseType(204)]
public async Task<IActionResult> GetRandomQuote([FromQuery] int? category_id = null)
{
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 query
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Skip(skip)
.Take(1)
.FirstOrDefaultAsync();
if (quote == null)
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Unknown error - couldn't get quote" });
Image? image = null;
if (quote.ImageId != 0)
{
image = await _db.Images.FirstOrDefaultAsync(i => i.Id == quote.ImageId);
}
var dto = new QuoteShortDTO
{
Id = quote.Id,
Text = quote.Text,
Author = quote.Author,
ImageUrl = image?.Url,
Categories = quote.QuoteCategories?
.Select(qc => qc.Category?.Name ?? "")
.Where(name => !string.IsNullOrEmpty(name))
.ToList() ?? new List<string>()
};
return Ok(dto);
}
// DELETE /api/v1/quotes/{id}