paginacja z kategoriami

This commit is contained in:
2025-07-21 13:25:22 +02:00
parent d502e9d120
commit f773f886b4

View File

@@ -1,192 +1,201 @@
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure; using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Update.Internal; using Microsoft.EntityFrameworkCore.Update.Internal;
using QuotifyBE.Data; using QuotifyBE.Data;
using QuotifyBE.DTOs; using QuotifyBE.DTOs;
using QuotifyBE.Entities; using QuotifyBE.Entities;
using QuotifyBE.Mapping; using QuotifyBE.Mapping;
using System.Reflection.Metadata.Ecma335; using System.Reflection.Metadata.Ecma335;
using System.Security.Claims; using System.Security.Claims;
namespace QuotifyBE.Controllers; namespace QuotifyBE.Controllers;
[ApiController] [ApiController]
[Route("api/v1/quotes")] [Route("api/v1/quotes")]
[Produces("application/json")] [Produces("application/json")]
public class QuotesController : ControllerBase public class QuotesController : ControllerBase
{ {
private readonly ApplicationDbContext _db; private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf; private readonly GeneralUseHelpers guhf;
public QuotesController(ApplicationDbContext db, GeneralUseHelpers GUHF) public QuotesController(ApplicationDbContext db, GeneralUseHelpers GUHF)
{ {
_db = db; _db = db;
guhf = GUHF; guhf = GUHF;
} }
// GET /api/v1/quotes // GET /api/v1/quotes
/// <summary> /// <summary>
/// Get a page of quotes /// Get a page of quotes
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// A page of quotes consists of 10 quotes or less. /// A page of quotes consists of 10 quotes or less.
/// If a page does not contain any quotes, an empty list is returned. /// If a page does not contain any quotes, an empty list is returned.
/// <br/><br/> /// <br/><br/>
/// <b>Important!</b> /// <b>Important!</b>
/// Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random. /// Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random.
/// </remarks> /// </remarks>
/// <param name="page_no">The page number</param> /// <param name="page_no">The page number</param>
/// <returns>A page (10 quotes)</returns> /// <returns>A page (10 quotes)</returns>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response> /// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet("page/{page_no}")] [HttpGet("page/{page_no}")]
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)] [ProducesResponseType(typeof(List<QuoteShortDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage(int page_no)
{
var totalQuotes = await _db.Quotes.CountAsync();
const int PageSize = 10;
if (page_no <= 0)
{
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Numer strony musi być większy niż 0" });
}
var quotes = await _db.Quotes
.Include(q => q.QuoteCategories)
.ThenInclude(qc => qc.Category)
.Include(q => q.User)
.Include(q => q.Image)
.OrderBy(q => q.Id)
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
var result = quotes
.Select(q => q.ToQuoteShortDTO())
.ToList();
return Ok(result);
}
// GET /api/v1/quotes/{id}
/// <summary>
/// [AUTHED] Get specified quote summary
/// </summary>
/// <remarks>
/// As per project's guidelines, requires a JWT.
/// </remarks>
/// <param name="id">The quote id in question</param>
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when quote id is invalid or simply doesn't exist</response>
[HttpGet("{id}")]
[Authorize]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuoteById(int id)
{
var quote = await _db.Quotes
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Include(q => q.User)
.Include(q => q.Image)
.FirstOrDefaultAsync(q => q.Id == id);
if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" });
return Ok(quote.ToQuoteShortDTO());
}
// POST /api/v1/quotes/new
/// <summary>
/// [AUTHED] Add a new quote
/// </summary>
/// <returns>Newly created quote's id</returns>
/// <param name="request">Form data containing required quote information</param>
/// <response code="201">Returned on valid request</response>
/// <response code="400">Returned when any of the categories does not exist</response>
/// <response code="403">Returned when user's id does not match the creator's id</response>
[HttpPost("new")]
[Authorize]
[EnableCors]
[ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 403)]
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
{
// Get user ID from claims
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
// https://stackoverflow.com/a/47708867
return StatusCode(403, new ErrorDTO { Status = "error", Error_msg = "Invalid user ID" });
// Find or create image
Image? image = null;
if (!string.IsNullOrEmpty(request.ImageUrl))
{
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl);
if (image == null)
{
image = new Image { Url = request.ImageUrl };
_db.Images.Add(image);
await _db.SaveChangesAsync();
}
}
// Create quote
var quote = new Quote
{
Text = request.Text,
Author = request.Author,
CreatedAt = DateTime.UtcNow,
LastUpdatedAt = DateTime.UtcNow,
ImageId = image?.Id ?? null,
UserId = userId,
QuoteCategories = new List<QuoteCategory>()
};
// Attach categories
foreach (var categoryId in request.CategoryIds ?? [])
{
Category? category = await _db.Categories.FirstOrDefaultAsync(c => c.Id == categoryId);
if (category == null)
return BadRequest(new ErrorDTO { Status = "error", Error_msg = $"Category ID {categoryId} not found" });
quote.QuoteCategories.Add(new QuoteCategory
{
Category = category,
Quote = quote
});
}
_db.Quotes.Add(quote);
await _db.SaveChangesAsync();
return CreatedAtAction(nameof(GetQuoteById), new { id = quote.Id }, quote.ToQuoteShortDTO());
}
// GET /api/v1/quotes/random
/// <summary>
/// Get a random quote summary
/// </summary>
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when no quotes exist</response>
[HttpGet("random")]
[AllowAnonymous]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)] [ProducesResponseType(typeof(ErrorDTO), 404)]
[ProducesResponseType(204)] public async Task<IActionResult> GetQuotePage(int page_no, [FromQuery] int? category_id = null)
{
const int PageSize = 10;
if (page_no <= 0)
{
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Numer strony musi być większy niż 0" });
}
// Paginacja bez filtra
var baseQuery = _db.Quotes
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Include(q => q.User)
.Include(q => q.Image)
.OrderBy(q => q.Id);
var pageQuotes = await baseQuery
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
// Filtrowanie dopiero po pobraniu strony
if (category_id.HasValue)
{
pageQuotes = pageQuotes
.Where(q => q.QuoteCategories!.Any(qc => qc.CategoryId == category_id.Value))
.ToList();
}
var result = pageQuotes
.Select(q => q.ToQuoteShortDTO())
.ToList();
return Ok(result);
}
// GET /api/v1/quotes/{id}
/// <summary>
/// [AUTHED] Get specified quote summary
/// </summary>
/// <remarks>
/// As per project's guidelines, requires a JWT.
/// </remarks>
/// <param name="id">The quote id in question</param>
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when quote id is invalid or simply doesn't exist</response>
[HttpGet("{id}")]
[Authorize]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuoteById(int id)
{
var quote = await _db.Quotes
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Include(q => q.User)
.Include(q => q.Image)
.FirstOrDefaultAsync(q => q.Id == id);
if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" });
return Ok(quote.ToQuoteShortDTO());
}
// POST /api/v1/quotes/new
/// <summary>
/// [AUTHED] Add a new quote
/// </summary>
/// <returns>Newly created quote's id</returns>
/// <param name="request">Form data containing required quote information</param>
/// <response code="201">Returned on valid request</response>
/// <response code="400">Returned when any of the categories does not exist</response>
/// <response code="403">Returned when user's id does not match the creator's id</response>
[HttpPost("new")]
[Authorize]
[EnableCors]
[ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 403)]
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
{
// Get user ID from claims
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
// https://stackoverflow.com/a/47708867
return StatusCode(403, new ErrorDTO { Status = "error", Error_msg = "Invalid user ID" });
// Find or create image
Image? image = null;
if (!string.IsNullOrEmpty(request.ImageUrl))
{
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl);
if (image == null)
{
image = new Image { Url = request.ImageUrl };
_db.Images.Add(image);
await _db.SaveChangesAsync();
}
}
// Create quote
var quote = new Quote
{
Text = request.Text,
Author = request.Author,
CreatedAt = DateTime.UtcNow,
LastUpdatedAt = DateTime.UtcNow,
ImageId = image?.Id ?? null,
UserId = userId,
QuoteCategories = new List<QuoteCategory>()
};
// Attach categories
foreach (var categoryId in request.CategoryIds ?? [])
{
Category? category = await _db.Categories.FirstOrDefaultAsync(c => c.Id == categoryId);
if (category == null)
return BadRequest(new ErrorDTO { Status = "error", Error_msg = $"Category ID {categoryId} not found" });
quote.QuoteCategories.Add(new QuoteCategory
{
Category = category,
Quote = quote
});
}
_db.Quotes.Add(quote);
await _db.SaveChangesAsync();
return CreatedAtAction(nameof(GetQuoteById), new { id = quote.Id }, quote.ToQuoteShortDTO());
}
// GET /api/v1/quotes/random
/// <summary>
/// Get a random quote summary
/// </summary>
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when no quotes exist</response>
[HttpGet("random")]
[AllowAnonymous]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
[ProducesResponseType(204)]
public async Task<IActionResult> GetRandomQuote([FromQuery] int? category_id = null) public async Task<IActionResult> GetRandomQuote([FromQuery] int? category_id = null)
{ {
IQueryable<Quote> query = _db.Quotes.Include(q => q.QuoteCategories!).ThenInclude(qc => qc.Category); IQueryable<Quote> query = _db.Quotes.Include(q => q.QuoteCategories!).ThenInclude(qc => qc.Category);
@@ -239,173 +248,173 @@ public class QuotesController : ControllerBase
return Ok(dto); return Ok(dto);
} }
// DELETE /api/v1/quotes/{id} // DELETE /api/v1/quotes/{id}
/// <summary> /// <summary>
/// [AUTHED] Delete a quote /// [AUTHED] Delete a quote
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Deletes a quote, granted it exists. <br/> /// Deletes a quote, granted it exists. <br/>
/// <br/> /// <br/>
/// <i> /// <i>
/// Is this the best practice? Marking the quote as hidden is also an option. /// Is this the best practice? Marking the quote as hidden is also an option.
/// </i> ~eee4 /// </i> ~eee4
/// </remarks> /// </remarks>
/// <returns>Json with status</returns> /// <returns>Json with status</returns>
/// <param name="id">Quote id which will be deleted</param> /// <param name="id">Quote id which will be deleted</param>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when no such quote exists</response> /// <response code="404">Returned when no such quote exists</response>
[HttpDelete("{id}")] [HttpDelete("{id}")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(200)] [ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 404)] [ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> DeleteQuote(int id) public async Task<IActionResult> DeleteQuote(int id)
{ {
// (Attempt to) find the quote // (Attempt to) find the quote
Quote? quote = await _db.Quotes Quote? quote = await _db.Quotes
.FirstOrDefaultAsync(q => q.Id == id); .FirstOrDefaultAsync(q => q.Id == id);
// Failed? // Failed?
if (quote == null) if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" }); return NotFound(new { status = "error", error_msg = "Quote not found" });
// If succeded, remove the quote // If succeded, remove the quote
_db.Quotes.Remove(quote); _db.Quotes.Remove(quote);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
// ====================================================================== // // ====================================================================== //
// Important! // // Important! //
// Is this the best we can do? Won't marking the quote as "hidden" // // Is this the best we can do? Won't marking the quote as "hidden" //
// be better than explicitly deleting it? ~eee4 // // be better than explicitly deleting it? ~eee4 //
// ====================================================================== // // ====================================================================== //
// Return ok // Return ok
return Ok(new { Status = "ok" }); return Ok(new { Status = "ok" });
} }
// PATCH /api/v1/quotes/{id} // PATCH /api/v1/quotes/{id}
/// <summary> /// <summary>
/// [AUTHED] Modify an existing quote /// [AUTHED] Modify an existing quote
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Modifies an existing quote. /// Modifies an existing quote.
/// <br/><br/> /// <br/><br/>
/// <b>Warning!</b> /// <b>Warning!</b>
/// We don't check the user id which created the quote. /// We don't check the user id which created the quote.
/// In case of single-user instances, this should not be a problem. /// In case of single-user instances, this should not be a problem.
/// This might become one, if we want users with non-admin roles; /// This might become one, if we want users with non-admin roles;
/// that would need some proper ACL checks here (with the help of GUHF). /// that would need some proper ACL checks here (with the help of GUHF).
/// <br/><br/> /// <br/><br/>
/// <b>Important!</b> /// <b>Important!</b>
/// Image handling works the same as with creating new quote. /// Image handling works the same as with creating new quote.
/// This means that images not present in the DB will be added automatically. /// This means that images not present in the DB will be added automatically.
/// <br/><br/> /// <br/><br/>
/// <b>Important!</b> /// <b>Important!</b>
/// "categories = null" is not the same as "categories = []"! /// "categories = null" is not the same as "categories = []"!
/// While "categories = null" will not alter the quote's categories, /// While "categories = null" will not alter the quote's categories,
/// "categories = []" will (and in turn, empty each and every present category)!<br/> /// "categories = []" will (and in turn, empty each and every present category)!<br/>
/// Be careful when handling user-provided categories! /// Be careful when handling user-provided categories!
/// </remarks> /// </remarks>
/// <returns>Newly modified quote as a DTO</returns> /// <returns>Newly modified quote as a DTO</returns>
/// <param name="id">Quote to be modified</param> /// <param name="id">Quote to be modified</param>
/// <param name="updatedQuote">Updated quote form data</param> /// <param name="updatedQuote">Updated quote form data</param>
/// <response code="204">Returned on valid request</response> /// <response code="204">Returned on valid request</response>
/// <response code="400">Returned when request text or author is empty (or whitespace)</response> /// <response code="400">Returned when request text or author is empty (or whitespace)</response>
/// <response code="404">Returned when no such quote exists</response> /// <response code="404">Returned when no such quote exists</response>
[HttpPatch("{id}")] [HttpPatch("{id}")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(QuoteShortDTO), 200)] [ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 400)] [ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 404)] [ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> EditQuote(int id, [FromBody] QuoteShortDTO updatedQuote) public async Task<IActionResult> EditQuote(int id, [FromBody] QuoteShortDTO updatedQuote)
{ {
// Try to find the quote in question // Try to find the quote in question
Quote? quote = await _db.Quotes Quote? quote = await _db.Quotes
.Include(q => q.QuoteCategories) .Include(q => q.QuoteCategories)
.FirstOrDefaultAsync(q => q.Id == id); .FirstOrDefaultAsync(q => q.Id == id);
// Failed? // Failed?
if (quote == null) if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" }); return NotFound(new { status = "error", error_msg = "Quote not found" });
// Is quote contents or author empty? // Is quote contents or author empty?
if (string.IsNullOrWhiteSpace(updatedQuote.Text) || string.IsNullOrWhiteSpace(updatedQuote.Author)) if (string.IsNullOrWhiteSpace(updatedQuote.Text) || string.IsNullOrWhiteSpace(updatedQuote.Author))
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "Text and author are required." }); return BadRequest(new ErrorDTO { Status = "error", Error_msg = "Text and author are required." });
// Alter the quote's content // Alter the quote's content
quote.Text = updatedQuote.Text; quote.Text = updatedQuote.Text;
quote.Author = updatedQuote.Author; quote.Author = updatedQuote.Author;
quote.LastUpdatedAt = DateTime.UtcNow; quote.LastUpdatedAt = DateTime.UtcNow;
// Try to find the image inside the DB // Try to find the image inside the DB
Image? image = null; Image? image = null;
if (!string.IsNullOrEmpty(updatedQuote.ImageUrl)) if (!string.IsNullOrEmpty(updatedQuote.ImageUrl))
{ {
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == updatedQuote.ImageUrl); image = await _db.Images.FirstOrDefaultAsync(i => i.Url == updatedQuote.ImageUrl);
// Failed? Just insert it yourself // Failed? Just insert it yourself
if (image == null) if (image == null)
{ {
image = new Image { Url = updatedQuote.ImageUrl }; image = new Image { Url = updatedQuote.ImageUrl };
_db.Images.Add(image); _db.Images.Add(image);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
} }
} }
quote.Image = image; quote.Image = image;
// Don't touch categories if they are explicitly null // Don't touch categories if they are explicitly null
if (updatedQuote.Categories == null) { } if (updatedQuote.Categories == null) { }
// If they aren't // If they aren't
else if (updatedQuote.Categories.Any()) else if (updatedQuote.Categories.Any())
{ {
// Get all the categories associated with a quote from DB // Get all the categories associated with a quote from DB
List<Category> categoriesFromDb = await _db.Categories List<Category> categoriesFromDb = await _db.Categories
.Where(c => updatedQuote.Categories.Contains(c.Name)) .Where(c => updatedQuote.Categories.Contains(c.Name))
.ToListAsync(); .ToListAsync();
// Determine which ones are already present, and which to add // Determine which ones are already present, and which to add
IEnumerable<string> existingNames = categoriesFromDb IEnumerable<string> existingNames = categoriesFromDb
.Select(c => c.Name); .Select(c => c.Name);
List<string> newNames = updatedQuote.Categories List<string> newNames = updatedQuote.Categories
.Except(existingNames) .Except(existingNames)
.ToList(); .ToList();
// For all the categories not present // For all the categories not present
foreach (var name in newNames) foreach (var name in newNames)
{ {
// Add them to the DB // Add them to the DB
var newCat = new Category { var newCat = new Category {
Name = name, Name = name,
Description = string.Empty, Description = string.Empty,
CreatedAt = DateTime.UtcNow CreatedAt = DateTime.UtcNow
}; };
_db.Categories.Add(newCat); _db.Categories.Add(newCat);
categoriesFromDb.Add(newCat); categoriesFromDb.Add(newCat);
} }
// If any categories were added, save changes // If any categories were added, save changes
if (newNames.Any()) if (newNames.Any())
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
// Assign all the new categories to the quote // Assign all the new categories to the quote
quote.QuoteCategories = categoriesFromDb quote.QuoteCategories = categoriesFromDb
.Select(cat => new QuoteCategory { .Select(cat => new QuoteCategory {
CategoryId = cat.Id, CategoryId = cat.Id,
QuoteId = quote.Id QuoteId = quote.Id
}) })
.ToList(); .ToList();
} }
else else
{ {
// No categories (empty list) inside DTO? // No categories (empty list) inside DTO?
// Clear them all! // Clear them all!
quote.QuoteCategories.Clear(); quote.QuoteCategories.Clear();
} }
// Save changes, return new quote as a DTO // Save changes, return new quote as a DTO
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return Ok(quote.ToQuoteShortDTO()); return Ok(quote.ToQuoteShortDTO());
} }
} }