feat: add API controllers for template and channel management
- ApiResponse<T>, ApiError in Api/Infrastructure - ApiControllerBase with IMediator, FromServiceResult, MapServiceError - EmailTemplatesController: GET list, GET one, POST, PUT, DELETE - EmailChannelsController: GET list, GET one, POST, PUT, DELETE Ref: IT-628 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
using HrynCo.NotificationService.Api.Infrastructure;
|
||||
using HrynCo.NotificationService.Services.Core;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace HrynCo.NotificationService.Api.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(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 } };
|
||||
}
|
||||
Reference in New Issue
Block a user