8 Commits

Author SHA1 Message Date
ba162c34cc chore: nitpicky details 2025-07-22 14:08:37 +02:00
197918e526 fix: keep API path names consistent 2025-07-22 14:01:32 +02:00
ac80061437 feat: paginate categories 2025-07-22 13:28:27 +02:00
e7cebc32a4 feat: naive sanity check for image URLs 2025-07-22 13:09:13 +02:00
9e1e9c86d3 feat: sort the quotes from newest first by default 2025-07-22 12:43:35 +02:00
10d2a35e61 Merge branch 'main' into Tydz3,-losowanie-z-kategoria 2025-07-22 12:06:44 +02:00
ca78f43f73 chore: documentation for category modification 2025-07-22 12:06:22 +02:00
3a82e4291e edycja kategorii 2025-07-22 11:45:48 +02:00
3 changed files with 113 additions and 21 deletions

View File

@@ -29,19 +29,20 @@ public class CategoryController : ControllerBase
// GET /api/v1/categories // GET /api/v1/categories
/// <summary> /// <summary>
/// Get every category /// Get a category page
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Can (and will) return an empty list if no categories are found in DB. <br/> /// Can (and will) return an empty list if no categories are found in DB. <br/>
/// Has CORS set. /// Has CORS set.
/// </remarks> /// </remarks>
/// <param name="page_no">The page number</param>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
// /// <response code="404">Returned when there are no categories to list</response> /// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet] [HttpGet("page/{page_no}")]
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)] [ProducesResponseType(typeof(CategoryShortDTO), 200)]
// [ProducesResponseType(typeof(ErrorDTO), 404)] [ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage() public async Task<IActionResult> GetCategoryPage(int page_no = 1)
{ {
// The following seems to be a bad idea, so I leave it as is. ~eee4 // The following seems to be a bad idea, so I leave it as is. ~eee4
// //
@@ -49,12 +50,23 @@ public class CategoryController : ControllerBase
// //
// if (totalCategories <= 0) // if (totalCategories <= 0)
// { // {
// return NotFound(new ErrorDTO { Status = "error", Error_msg = "No categories to list" }); // return NoContent(new ErrorDTO { Status = "error", Error_msg = "No categories to list" });
// } // }
const int PageSize = 10;
if (page_no <= 0)
{
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Numer strony musi być większy niż 0" });
}
// Get all the categories // Get all the categories
//List<Category> categories = await _db.Categories
// .ToListAsync();
List<Category> categories = await _db.Categories List<Category> categories = await _db.Categories
.ToListAsync(); .Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
// Convert them to a list of DTO // Convert them to a list of DTO
List<CategoryShortDTO> result = categories List<CategoryShortDTO> result = categories
@@ -155,8 +167,49 @@ public class CategoryController : ControllerBase
return Ok(new { Status = "ok" }); return Ok(new { Status = "ok" });
} }
// TODO: Update category
// PATCH /api/v1/categories/1 // PATCH /api/v1/categories/1
/// <summary>
/// [AUTHED] Modify an existing category
/// </summary>
/// <remarks>
/// Allows authorized users to modify categories.
/// <br/><br/>
/// Has CORS set.
/// </remarks>
/// <param name="id">Id of the category which shall be modified</param>
/// <param name="updatedCategory">DTO with new name and description. Id and creation date are ignored.</param>
/// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when category name is empty or null</response>
/// <response code="404">Returned when no such category exists</response>
[HttpPatch("{id}")]
[Authorize]
[EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> EditCategory(int id, [FromBody] CategoryShortDTO updatedCategory)
{
// Find the category to modify
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Id == id);
// Failed?
if (cat == null)
return NotFound(new { status = "error", error_msg = "Category not found" });
// Otherwise, ensure the category name is not empty or null
if (string.IsNullOrWhiteSpace(updatedCategory.Name))
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "Category name cannot be empty." });
// Update the fields
cat.Name = updatedCategory.Name;
cat.Description = updatedCategory.Description;
// Note the user cannot modify the createdAt field,
// and we do not store last modification date.
await _db.SaveChangesAsync();
// Return the modified category to user
return Ok(cat.ToCategoryShortDTO());
}
} }

View File

@@ -1,14 +1,11 @@
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
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 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.Security.Claims; using System.Security.Claims;
namespace QuotifyBE.Controllers; namespace QuotifyBE.Controllers;
@@ -41,6 +38,7 @@ public class QuotesController : ControllerBase
/// 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>
/// <param name="sort">How to sort the results (desc/asc)</param>
/// <param name="category_id">(Optional) Standalone category id or comma separated ids (e.g. "1" or "1,2,3")</param> /// <param name="category_id">(Optional) Standalone category id or comma separated ids (e.g. "1" or "1,2,3")</param>
/// <returns>A page (&lt;= 10 quotes)</returns> /// <returns>A page (&lt;= 10 quotes)</returns>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
@@ -49,7 +47,7 @@ public class QuotesController : ControllerBase
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)] [ProducesResponseType(typeof(List<QuoteShortDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)] [ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage(int page_no, [FromQuery] string? category_id = null) public async Task<IActionResult> GetQuotePage(int page_no = 1, string? sort = "desc", [FromQuery] string? category_id = null)
{ {
var totalQuotes = await _db.Quotes.CountAsync(); var totalQuotes = await _db.Quotes.CountAsync();
const int PageSize = 10; const int PageSize = 10;
@@ -80,8 +78,15 @@ public class QuotesController : ControllerBase
.Include(q => q.QuoteCategories!) .Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category) .ThenInclude(qc => qc.Category)
.Include(q => q.User) .Include(q => q.User)
.Include(q => q.Image) .Include(q => q.Image);
.OrderBy(q => q.Id);
// Sort the results in ascending/descending order by id
IOrderedQueryable<Quote>? orderedQuery;
if (sort != null && sort.Equals("asc"))
orderedQuery = baseQuery.OrderBy(q => q.Id);
else
// Sort in descending order by default
orderedQuery = baseQuery.OrderByDescending(q => q.Id);
// Botched solution // Botched solution
List<Quote> pageQuotes; List<Quote> pageQuotes;
@@ -89,7 +94,7 @@ public class QuotesController : ControllerBase
// Filtrowanie przed pobraniem strony // Filtrowanie przed pobraniem strony
if (categories != null) if (categories != null)
{ {
pageQuotes = await baseQuery pageQuotes = await orderedQuery
.Where(q => q.QuoteCategories! .Where(q => q.QuoteCategories!
.Any(qc => categories.Contains(qc.CategoryId)) .Any(qc => categories.Contains(qc.CategoryId))
//.Any(qc => qc.CategoryId == category_id.Value) //.Any(qc => qc.CategoryId == category_id.Value)
@@ -100,7 +105,7 @@ public class QuotesController : ControllerBase
} }
else else
{ {
pageQuotes = await baseQuery pageQuotes = await orderedQuery
.Skip((page_no - 1) * PageSize) .Skip((page_no - 1) * PageSize)
.Take(PageSize) .Take(PageSize)
.ToListAsync(); .ToListAsync();
@@ -150,32 +155,50 @@ public class QuotesController : ControllerBase
/// [AUTHED] Add a new quote /// [AUTHED] Add a new quote
/// </summary> /// </summary>
/// <returns>Newly created quote's id</returns> /// <returns>Newly created quote's id</returns>
/// <remarks>
/// <b>Note</b>:
/// User-provided image URLs are validated by checking
/// if they start with "https://", "http://" or "/".
/// This is rather a naive solution.
/// </remarks>
/// <param name="request">Form data containing required quote information</param> /// <param name="request">Form data containing required quote information</param>
/// <response code="201">Returned on valid request</response> /// <response code="201">Returned on valid request</response>
/// <response code="400">Returned when any of the categories does not exist</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> /// <response code="403">Returned when user's id does not match the creator's id</response>
/// <response code="406">Returned when image url is invalid (does not start with "https://", "http://", or "/")</response>
[HttpPost("new")] [HttpPost("new")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(201)] [ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)] [ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 403)] [ProducesResponseType(typeof(ErrorDTO), 403)]
[ProducesResponseType(typeof(ErrorDTO), 406)]
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request) public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
{ {
// Get user ID from claims // Get user ID from claims
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId)) if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
// https://stackoverflow.com/a/47708867 // https://stackoverflow.com/a/47708867
return StatusCode(403, new ErrorDTO { Status = "error", Error_msg = "Invalid user ID" }); return StatusCode(403, new ErrorDTO { Status = "error", Error_msg = "Invalid user ID" });
// Find or create image // Try to find the image inside the DB
Image? image = null; Image? image = null;
if (!string.IsNullOrEmpty(request.ImageUrl)) if (!string.IsNullOrEmpty(request.ImageUrl))
{ {
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl); image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl);
// Failed? Just insert it yourself
if (image == null) if (image == null)
{ {
// Simple (naive) sanity check for image URLs
if ( !request.ImageUrl.StartsWith("http://")
&& !request.ImageUrl.StartsWith("https://")
&& !request.ImageUrl.StartsWith("/"))
return StatusCode(406, new ErrorDTO {
Status = "error",
Error_msg = "Image URLs should point to http/https url or a local resource"
});
image = new Image { Url = request.ImageUrl }; image = new Image { Url = request.ImageUrl };
_db.Images.Add(image); _db.Images.Add(image);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -339,13 +362,19 @@ public class QuotesController : ControllerBase
/// 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!
/// <br/><br/>
/// <b>Note</b>:
/// User-provided image URLs are validated by checking
/// if they start with "https://", "http://" or "/".
/// This is rather a naive solution.
/// </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. Id is ignored.</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>
/// <response code="406">Returned when image url is invalid (does not start with "https://", "http://", or "/")</response>
[HttpPatch("{id}")] [HttpPatch("{id}")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
@@ -377,9 +406,19 @@ public class QuotesController : ControllerBase
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)
{ {
// Simple (naive) sanity check for image URLs
if ( !updatedQuote.ImageUrl.StartsWith("http://")
&& !updatedQuote.ImageUrl.StartsWith("https://")
&& !updatedQuote.ImageUrl.StartsWith("/"))
return StatusCode(406, new ErrorDTO {
Status = "error",
Error_msg = "Image URLs should point to http/https url or a local resource"
});
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();

View File

@@ -10,12 +10,12 @@ namespace QuotifyBE.Controllers;
[EnableCors] [EnableCors]
[Route("api/v1/stats")] [Route("api/v1/stats")]
[Produces("application/json")] [Produces("application/json")]
public class StatisticController : ControllerBase public class StatisticsController : ControllerBase
{ {
private readonly ApplicationDbContext _db; private readonly ApplicationDbContext _db;
public StatisticController( ApplicationDbContext db) public StatisticsController( ApplicationDbContext db)
{ {
_db = db; _db = db;
} }