Files
API/TOOHUCardAPI/Controllers/MethodBasedController.cs
2021-10-26 00:26:52 -04:00

60 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TOOHUCardAPI.Data;
using MethodMap = System.Collections.Generic.Dictionary<string, System.Reflection.MethodInfo>;
namespace TOOHUCardAPI.Controllers
{
public class MethodBasedController : ControllerBase
{
public delegate Task<object> EndpointHandler(string requestBody);
private static Dictionary<Type, MethodMap> MethodMapByType = new Dictionary<Type, MethodMap>();
protected Task<object> InvokeEndpointHandlerForMethod<T>(object _this, string method, string body)
{
MethodMap registeredEndpointHandlers = GetMethodMapForType<T>();
if (registeredEndpointHandlers.ContainsKey(method))
{
return ((EndpointHandler) registeredEndpointHandlers[method]
.CreateDelegate(typeof(EndpointHandler), _this))(body);
}
throw new MissingEndpointHandlerException(method);
}
private MethodMap GetMethodMapForType<T>()
{
if (!MethodMapByType.ContainsKey(typeof(T)))
{
MethodMapByType[typeof(T)] = RegisterEndpointHandlers<T>();
}
return MethodMapByType[typeof(T)];
}
private static MethodMap RegisterEndpointHandlers<T>()
{
MethodInfo[] methods = typeof(T).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
return methods
.Aggregate(new MethodMap(), (handlers, m) =>
{
Attribute attr = m.GetCustomAttribute(typeof(EndpointHandlerAttribute), false);
if (attr != null)
{
EndpointHandlerAttribute e = (EndpointHandlerAttribute) attr;
handlers.Add(e.Method, m);
}
return handlers;
});
}
}
public class MissingEndpointHandlerException : Exception
{
public MissingEndpointHandlerException(string method) : base($"Handler for [{method}] is either missing or incorrectly setup.")
{
}
}
}