Repository navigation
Expand file tree
/
Copy pathBaseController.cs
More file actions
51 lines (42 loc) · 1.73 KB
/
Copy pathBaseController.cs
File metadata and controls
51 lines (42 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using API.Models;
using Core.Domain.Interfaces;
using Core.Domain.Notifications;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Produces("application/json")]
public class BaseController : ControllerBase
{
protected readonly DomainNotificationHandler _notifications;
private readonly IMediatorHandler _mediator;
protected BaseController(INotificationHandler<DomainNotification> notifications, IUser user, IMediatorHandler mediator)
{
_notifications = (DomainNotificationHandler)notifications ?? throw new System.ArgumentNullException(nameof(notifications));
_mediator = mediator ?? throw new System.ArgumentNullException(nameof(mediator));
}
protected new IActionResult Response(object? result = null, string? errorMessage = null)
{
if (IsValid())
return Ok(result);
var errorResponse = new ErrorResponse(errorMessage ?? "Erro");
foreach (var error in _notifications.GetNotifications())
errorResponse.AddError(error.Key, error.Value);
return BadRequest(errorResponse);
}
protected bool IsValid() =>
!_notifications.HasNotifications();
protected void NotifyInvalidViewModelErrors()
{
var errors = ModelState.Values.SelectMany(p => p.Errors);
foreach (var error in errors)
{
var errorMessage = error.Exception == null ? error.ErrorMessage : error.Exception.Message;
_mediator.RaiseEvent(new DomainNotification(nameof(error), error.ErrorMessage));
}
}
}
}