mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 22:10:05 +01:00
losowanie cytatow
This commit is contained in:
63
Controllers/RandomQuoteController.cs
Normal file
63
Controllers/RandomQuoteController.cs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using QuotifyBE.Data;
|
||||||
|
using QuotifyBE.Entities;
|
||||||
|
namespace QuotifyBE.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("controller")]
|
||||||
|
public class QuotesController_2 : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly ApplicationDbContext _db;
|
||||||
|
|
||||||
|
public QuotesController_2(ApplicationDbContext db)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
}
|
||||||
|
[HttpGet]
|
||||||
|
[AllowAnonymous]
|
||||||
|
|
||||||
|
public async Task<IActionResult> GetRandomQuote()
|
||||||
|
{
|
||||||
|
var totalQuotes = await _db.Quotes.CountAsync();
|
||||||
|
if (totalQuotes == 0)
|
||||||
|
return NotFound(new { status = "error", error_msg = "brak cytatow" });
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
Image? image = null;
|
||||||
|
if (quote.ImageId != 0)
|
||||||
|
{
|
||||||
|
image = await _db.Images.FirstOrDefaultAsync(i => i.Id == quote.ImageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
var dto = new RandomQuote
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
9
DTOs/RandomQuote.cs
Normal file
9
DTOs/RandomQuote.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
public record class RandomQuote
|
||||||
|
{
|
||||||
|
public string Text { get; set; } = string.Empty;
|
||||||
|
public string Author { get; set; } = string.Empty;
|
||||||
|
public string? ImageUrl { get; set; }
|
||||||
|
public List<string> Categories { get; set; } = new();
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
Reference in New Issue
Block a user