Add episodes controller

This commit is contained in:
2020-02-29 16:01:22 +01:00
parent 0cef2e3df2
commit 54c0fb2fd2
10 changed files with 190 additions and 23 deletions

View File

@@ -21,6 +21,7 @@ namespace EstusShots.Client
// API Routes // API Routes
public Seasons Seasons { get; } public Seasons Seasons { get; }
public Episodes Episodes { get; }
/// <summary> /// <summary>
/// Creates a new instance of <see cref="EstusShotsClient"/> /// Creates a new instance of <see cref="EstusShotsClient"/>
@@ -32,6 +33,7 @@ namespace EstusShots.Client
HttpClient = new HttpClient {Timeout = TimeSpan.FromSeconds(10)}; HttpClient = new HttpClient {Timeout = TimeSpan.FromSeconds(10)};
Seasons = new Seasons(this); Seasons = new Seasons(this);
Episodes = new Episodes(this);
} }
/// <summary> /// <summary>

View File

@@ -0,0 +1,24 @@
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using EstusShots.Shared.Interfaces;
using EstusShots.Shared.Models;
using EstusShots.Shared.Models.Parameters;
namespace EstusShots.Client.Routes
{
public class Episodes : IEpisodesController
{
private readonly EstusShotsClient _client;
public Episodes(EstusShotsClient client)
{
_client = client;
}
private string ActionUrl([CallerMemberName]string caller = "") =>
$"{_client.ApiUrl}{nameof(Episodes)}/{caller}";
public async Task<ApiResponse<GetEpisodesResponse>> GetEpisodes(GetEpisodesParameter parameter)
=> await _client.PostToApi<GetEpisodesResponse, GetEpisodesParameter>(ActionUrl(), parameter);
}
}

View File

@@ -55,10 +55,14 @@ namespace EstusShots.Gtk
private EstusShotsClient Client { get; } private EstusShotsClient Client { get; }
private BindableListControl<Season> SeasonsControl { get; } private BindableListControl<Season> SeasonsControl { get; }
private void SeasonsViewOnOnSelectionChanged(object sender, SelectionChangedEventArgs e) private async void SeasonsViewOnOnSelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
if (!(e.Selection is Season season)) return; if (!(e.Selection is Season season)) return;
Info($"Season '{season.DisplayName}' selected");
// TODO this is test code
var parameter = new GetEpisodesParameter(season.SeasonId);
var res = await Client.Episodes.GetEpisodes(parameter);
Info($"{season.DisplayName}: {res.Data.Episodes.Count} episodes");
} }
private async void NewSeasonButtonOnClicked(object sender, EventArgs e) private async void NewSeasonButtonOnClicked(object sender, EventArgs e)

View File

@@ -1,38 +1,39 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using AutoMapper;
using EstusShots.Server.Services; using EstusShots.Server.Services;
using EstusShots.Shared.Interfaces;
using EstusShots.Shared.Models;
using EstusShots.Shared.Models.Parameters;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Dto = EstusShots.Shared.Dto;
namespace EstusShots.Server.Controllers namespace EstusShots.Server.Controllers
{ {
[ApiController] [ApiController]
[Route("/api/[controller]")] [Route("/api/[controller]/[action]")]
public class EpisodesController : ControllerBase public class EpisodesController : ControllerBase, IEpisodesController
{ {
private readonly EstusShotsContext _context;
private readonly IMapper _mapper;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly EpisodesService _episodesService;
public EpisodesController(ILogger<EpisodesController> logger, IMapper mapper, EstusShotsContext context) public EpisodesController(ILogger<EpisodesController> logger, EpisodesService episodesService)
{ {
_logger = logger; _logger = logger;
_mapper = mapper; _episodesService = episodesService;
_context = context;
} }
[HttpGet("seasonId")] public async Task<ApiResponse<GetEpisodesResponse>> GetEpisodes(GetEpisodesParameter parameter)
public async Task<ActionResult<List<Dto.Episode>>> GetEpisodes(Guid seasonId) {
{ try
_logger.LogDebug($"All"); {
var episodes = await _context.Episodes.Where(x => x.SeasonId == seasonId).ToListAsync(); _logger.LogInformation($"Request received from client '{Request.HttpContext.Connection.RemoteIpAddress}'");
var dtos = _mapper.Map<List<Dto.Episode>>(episodes); return await _episodesService.GetEpisodes(parameter);
return dtos; }
catch (Exception e)
{
_logger.LogError(e, "Exception Occured");
return new ApiResponse<GetEpisodesResponse>(new OperationResult(e));
}
} }
} }
} }

View File

@@ -0,0 +1,21 @@
using System;
using System.Net;
using EstusShots.Shared.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace EstusShots.Server.Filters
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var code = HttpStatusCode.InternalServerError;
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = (int)code;
var response = new ApiResponse<CriticalErrorResponse>(new OperationResult(false, "Critical Server Error", context.Exception.Message));
context.Result = new JsonResult(response);
}
}
}

View File

@@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using EstusShots.Shared.Interfaces;
using EstusShots.Shared.Models;
using EstusShots.Shared.Models.Parameters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Dto = EstusShots.Shared.Dto;
namespace EstusShots.Server.Services
{
public class EpisodesService : IEpisodesController
{
private readonly ILogger _logger;
private readonly EstusShotsContext _context;
private readonly IMapper _mapper;
public EpisodesService(ILogger<EpisodesService> logger, EstusShotsContext context, IMapper mapper)
{
_logger = logger;
_context = context;
_mapper = mapper;
}
public async Task<ApiResponse<GetEpisodesResponse>> GetEpisodes(GetEpisodesParameter parameter)
{
var episodes = await _context.Episodes
.Where(x => x.SeasonId == parameter.SeasonId)
.ToListAsync();
var dtos = _mapper.Map<List<Dto.Episode>>(episodes);
_logger.LogInformation($"{dtos.Count} episodes loaded for season '{parameter.SeasonId}'");
return new ApiResponse<GetEpisodesResponse>(new GetEpisodesResponse(dtos));
}
}
}

View File

@@ -29,6 +29,7 @@ namespace EstusShots.Server
services.AddAutoMapper(typeof(Startup)); services.AddAutoMapper(typeof(Startup));
services.AddControllers().AddJsonOptions(options => services.AddControllers().AddJsonOptions(options =>
{ {
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
if (IsDevelopment) if (IsDevelopment)
{ {
options.JsonSerializerOptions.WriteIndented = true; options.JsonSerializerOptions.WriteIndented = true;
@@ -38,7 +39,10 @@ namespace EstusShots.Server
{ {
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Estus Shots API", Version = "v1" }); options.SwaggerDoc("v1", new OpenApiInfo { Title = "Estus Shots API", Version = "v1" });
}); });
// Register business logic services
services.AddScoped<SeasonsService>(); services.AddScoped<SeasonsService>();
services.AddScoped<EpisodesService>();
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -65,6 +69,7 @@ namespace EstusShots.Server
app.UseRouting(); app.UseRouting();
app.UseAuthorization(); app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
} }
} }

View File

@@ -0,0 +1,19 @@
using System.Threading.Tasks;
using EstusShots.Shared.Models;
using EstusShots.Shared.Models.Parameters;
namespace EstusShots.Shared.Interfaces
{
/// <summary>
/// Access to episodes
/// </summary>
public interface IEpisodesController
{
/// <summary>
/// Load all episodes for a season
/// </summary>
/// <param name="parameter">The parameter object</param>
/// <returns>The GetEpisodes response object</returns>
Task<ApiResponse<GetEpisodesResponse>> GetEpisodes(GetEpisodesParameter parameter);
}
}

View File

@@ -1,4 +1,5 @@
using System; using System;
using EstusShots.Shared.Interfaces;
namespace EstusShots.Shared.Models namespace EstusShots.Shared.Models
{ {
@@ -60,4 +61,6 @@ namespace EstusShots.Shared.Models
Data = data; Data = data;
} }
} }
public class CriticalErrorResponse :IApiResponse{}
} }

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using EstusShots.Shared.Dto;
using EstusShots.Shared.Interfaces;
namespace EstusShots.Shared.Models.Parameters
{
// GetEpisodes
/// <summary>
/// Parameter class for loading all episodes for a season
/// </summary>
public class GetEpisodesParameter : IApiParameter
{
/// <summary>
/// ID of the season for which to load the episode list
/// </summary>
public Guid SeasonId { get; set; }
public GetEpisodesParameter(Guid seasonId)
{
SeasonId = seasonId;
}
public GetEpisodesParameter()
{
SeasonId = Guid.Empty;
}
}
/// <summary>
/// Parameter class returned from the API with all loaded episodes for a season
/// </summary>
public class GetEpisodesResponse : IApiResponse
{
/// <summary>
/// List of all episodes in the requested season
/// </summary>
public List<Episode> Episodes { get; set; }
public GetEpisodesResponse(List<Episode> episodes)
{
Episodes = episodes;
}
public GetEpisodesResponse()
{
Episodes = new List<Episode>();
}
}
}