Files
hrynco-notification-service/HrynCo.NotificationService.Web/Controllers/ApiControllerBase.cs
T
Anatolii Grynchuk ab44ad117c refactor: rename Api project to Web
- HrynCo.NotificationService.Api -> HrynCo.NotificationService.Web
- HrynCo.NotificationService.Api.IntegrationTests -> HrynCo.NotificationService.Web.IntegrationTests
- Updated slnx, docker-compose, project references, and namespaces
- Project serves both REST API and admin UI

Ref: IT-628

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-02 01:55:57 +03:00

46 lines
1.8 KiB
C#

using HrynCo.NotificationService.Web.Infrastructure;
using HrynCo.NotificationService.Services.Core;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace HrynCo.NotificationService.Web.Controllers;
[Route("api/v1/[controller]")]
[ApiController]
public abstract class ApiControllerBase : ControllerBase
{
protected ApiControllerBase(IMediator mediator)
{
Mediator = mediator;
}
protected IMediator Mediator { get; }
protected IActionResult FromServiceResult<T>(ServiceResult<T> result) =>
result.IsSuccess
? Ok(new ApiResponse<T> { Success = true, Data = result.Result })
: MapServiceError(result.Error!);
protected IActionResult CreatedFromServiceResult<T>(ServiceResult<Guid> result, string actionName, Func<Guid, T> routeValues) =>
result.IsSuccess
? CreatedAtAction(actionName, routeValues(result.Result), new ApiResponse<Guid> { Success = true, Data = result.Result })
: MapServiceError(result.Error!);
protected IActionResult MapServiceError(ServiceError error)
{
string code = error.Code?.ToString() ?? "Unknown";
return error.Code switch
{
ServiceErrorCode.NotFound => NotFound(ErrorResponse(code, error.Message)),
ServiceErrorCode.Conflict => Conflict(ErrorResponse(code, error.Message)),
ServiceErrorCode.InvalidRequest => BadRequest(ErrorResponse(code, error.Message)),
null => throw new InvalidOperationException("Error code was null for failed result."),
_ => throw new ArgumentOutOfRangeException(nameof(error), error, "Unexpected error code.")
};
}
private static ApiResponse<object> ErrorResponse(string code, string message) =>
new() { Success = false, Error = new ApiError { Code = code, Message = message } };
}