using System;
using System.Threading.Tasks;
using EstusShots.Shared.Interfaces;
using EstusShots.Shared.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace EstusShots.Server.Controllers
{
///
/// Base class for all API controllers.
/// Contains shared methods and properties that get used by the generated code.
///
public abstract class BaseController : ControllerBase
{
private readonly ILogger _logger;
protected BaseController(ILogger logger)
{
_logger = logger;
}
///
/// Generic method to handle the boilerplate code when calling an api service.
///
/// Function that calls an API service
/// A response parameter that implements
/// An
protected async Task> ServiceCall(Func>> serviceCall)
where T : class, IApiResponse, new()
{
try
{
if (!ModelState.IsValid) _logger.LogError($"Model invalid");
_logger.LogInformation($"Request received from client '{Request.HttpContext.Connection.RemoteIpAddress}'");
return await serviceCall();
}
catch (Exception e)
{
_logger.LogError(e, "Exception Occured");
return new ApiResponse(new OperationResult(e));
}
}
}
}