2020-11-11 18:31:26 -05:00
|
|
|
|
using SharedLibraryCore.Interfaces;
|
2019-07-27 09:18:49 -04:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Threading.Tasks;
|
2020-11-11 18:31:26 -05:00
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
2019-07-27 09:18:49 -04:00
|
|
|
|
|
|
|
|
|
namespace IW4MAdmin.Application.Misc
|
|
|
|
|
{
|
|
|
|
|
class MiddlewareActionHandler : IMiddlewareActionHandler
|
|
|
|
|
{
|
2020-01-13 21:06:57 -05:00
|
|
|
|
private readonly IDictionary<string, IList<object>> _actions;
|
|
|
|
|
private readonly ILogger _logger;
|
2019-07-27 09:18:49 -04:00
|
|
|
|
|
2020-11-11 18:31:26 -05:00
|
|
|
|
public MiddlewareActionHandler(ILogger<MiddlewareActionHandler> logger)
|
2020-01-13 21:06:57 -05:00
|
|
|
|
{
|
|
|
|
|
_actions = new Dictionary<string, IList<object>>();
|
|
|
|
|
_logger = logger;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Executes the action with the given name
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <typeparam name="T">Execution return type</typeparam>
|
|
|
|
|
/// <param name="value">Input value</param>
|
|
|
|
|
/// <param name="name">Name of action to execute</param>
|
|
|
|
|
/// <returns></returns>
|
2019-07-27 09:18:49 -04:00
|
|
|
|
public async Task<T> Execute<T>(T value, string name = null)
|
|
|
|
|
{
|
|
|
|
|
string key = string.IsNullOrEmpty(name) ? typeof(T).ToString() : name;
|
|
|
|
|
|
|
|
|
|
if (_actions.ContainsKey(key))
|
|
|
|
|
{
|
|
|
|
|
foreach (var action in _actions[key])
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
value = await ((IMiddlewareAction<T>)action).Invoke(value);
|
|
|
|
|
}
|
2020-01-13 21:06:57 -05:00
|
|
|
|
catch (Exception e)
|
|
|
|
|
{
|
2020-11-11 18:31:26 -05:00
|
|
|
|
_logger.LogWarning(e, "Failed to invoke middleware action {name}", name);
|
2020-01-13 21:06:57 -05:00
|
|
|
|
}
|
2019-07-27 09:18:49 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
2020-01-13 21:06:57 -05:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Registers an action by name
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <typeparam name="T"></typeparam>
|
|
|
|
|
/// <param name="actionType">Action type specifier</param>
|
|
|
|
|
/// <param name="action">Action to perform</param>
|
|
|
|
|
/// <param name="name">Name of action</param>
|
2019-07-27 09:18:49 -04:00
|
|
|
|
public void Register<T>(T actionType, IMiddlewareAction<T> action, string name = null)
|
|
|
|
|
{
|
|
|
|
|
string key = string.IsNullOrEmpty(name) ? typeof(T).ToString() : name;
|
|
|
|
|
|
|
|
|
|
if (_actions.ContainsKey(key))
|
|
|
|
|
{
|
|
|
|
|
_actions[key].Add(action);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
_actions.Add(key, new[] { action });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|