2020-01-13 21:06:57 -05:00
|
|
|
|
using SharedLibraryCore;
|
|
|
|
|
using SharedLibraryCore.Interfaces;
|
2019-07-27 09:18:49 -04:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
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-01-13 21:06:57 -05:00
|
|
|
|
public MiddlewareActionHandler(ILogger logger)
|
|
|
|
|
{
|
|
|
|
|
_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)
|
|
|
|
|
{
|
|
|
|
|
_logger.WriteWarning($"Failed to invoke middleware action {name}");
|
|
|
|
|
_logger.WriteDebug(e.GetExceptionInfo());
|
|
|
|
|
}
|
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 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|