🥅 handled input errors in API

Co-authored-by: Sindre Kjelsrud <kjelsrudsindre@gmail.com>
This commit is contained in:
haraldnilsen 2023-09-19 13:45:34 +02:00
parent 4f063495f2
commit 983a6af41a

View file

@ -1,7 +1,8 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Writers;
namespace backend.Controllers;
namespace backend;
using static backend.QueryParameterValidators;
[ApiController]
[Route("[controller]")]
@ -9,6 +10,10 @@ public class MovieController: ControllerBase
{
private readonly MovieDbContext _context;
private readonly ILogger<MovieController> _logger;
private static readonly string[] sortTypes = new[]
{
"titleasc", "titledesc", "yearasc", "yeardesc"
};
public MovieController(ILogger<MovieController> logger, MovieDbContext context)
{
@ -18,31 +23,39 @@ public class MovieController: ControllerBase
[HttpGet(Name = "GetMovies")]
public ActionResult<IEnumerable<MovieDB>> Get(
[FromQuery] string? s,
[FromQuery] string s,
[FromQuery] string? type,
[FromQuery] string? y,
[FromQuery] string? sort,
[FromQuery] int pageNumber = 1,
[FromQuery] int pageSize = 5
) {
try
{
if (s == "") {
return StatusCode(400, "Bad Request");
}
if (IsValidS(s)) return StatusCode(400, "Bad Request: Invalid title");
var movies = _context.Movies.Where(m => m.Title.Contains(s.ToLower()));
if (type != null) {
if (!IsValidType(type)) return StatusCode(400, "Bad Request: Invalid type");
movies = movies.Where(m => m.Type == type);
}
if (y != null) {
if (!IsValidYear(y)) return StatusCode(400, "Bad Request: Invalid year");
movies = movies.Where(m => m.Year == y);
}
if (sort != null) {
if (!IsValidSort(sort)) return StatusCode(400, "Bad Request: Invalid sort-type");
}
if (!IsValidPageNumber(pageNumber) || !IsValidPageSize(pageSize))
return StatusCode(400, "Bad Request: Invalid page-size or page-number");
var totalMovies = movies.Count();
var totalPages = Math.Ceiling((double)totalMovies / pageSize);
IEnumerable<MovieDB> resultSkip = movies.Skip(pageSize * (pageNumber - 1));
IEnumerable<MovieDB> resultTake = resultSkip.Take(pageSize);