| | | 1 | | using Syki.Back.Webhooks; |
| | | 2 | | |
| | | 3 | | namespace Syki.Back.Configs; |
| | | 4 | | |
| | | 5 | | public static class WebhookConfigs |
| | | 6 | | { |
| | 0 | 7 | | private static readonly Dictionary<string, Type> _eventTypes = []; |
| | | 8 | | |
| | | 9 | | public static void AddWebhookEventConfigs(this WebApplicationBuilder builder) |
| | | 10 | | { |
| | 0 | 11 | | var assemblies = AppDomain.CurrentDomain.GetAssemblies() |
| | 0 | 12 | | .Where(s => s.FullName!.StartsWith("Back")) |
| | 0 | 13 | | .ToList(); |
| | | 14 | | |
| | 0 | 15 | | var eventTypes = assemblies.SelectMany(s => s.GetTypes()) |
| | 0 | 16 | | .Where(t => t.IsAssignableTo(typeof(IWebhookEvent)) && !t.IsInterface) |
| | 0 | 17 | | .ToList(); |
| | | 18 | | |
| | 0 | 19 | | foreach (var type in eventTypes) |
| | | 20 | | { |
| | 0 | 21 | | var attr = type.GetCustomAttributes(typeof(WebhookEventTypeAttribute), false) |
| | 0 | 22 | | .Cast<WebhookEventTypeAttribute>() |
| | 0 | 23 | | .FirstOrDefault(); |
| | | 24 | | |
| | 0 | 25 | | if (attr == null) throw new InvalidOperationException($"IWebhookEvent '{type.Name}' is missing [WebhookEvent |
| | | 26 | | |
| | 0 | 27 | | _eventTypes[attr.Type] = type; |
| | | 28 | | } |
| | | 29 | | |
| | 0 | 30 | | var handlerTypes = assemblies.SelectMany(s => s.GetTypes()) |
| | 0 | 31 | | .Where(t => !t.IsInterface && t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == |
| | 0 | 32 | | .ToList(); |
| | | 33 | | |
| | 0 | 34 | | var handledEventTypes = new HashSet<Type>(); |
| | | 35 | | |
| | 0 | 36 | | foreach (var type in handlerTypes) |
| | | 37 | | { |
| | 0 | 38 | | var handlerInterface = type.GetInterfaces() |
| | 0 | 39 | | .First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IWebhookEventHandler<>)); |
| | | 40 | | |
| | 0 | 41 | | handledEventTypes.Add(handlerInterface.GetGenericArguments()[0]); |
| | 0 | 42 | | builder.Services.AddTransient(handlerInterface, type); |
| | | 43 | | } |
| | | 44 | | |
| | 0 | 45 | | var eventsWithoutHandler = eventTypes.Except(handledEventTypes).ToList(); |
| | 0 | 46 | | if (eventsWithoutHandler.Count > 0) |
| | | 47 | | { |
| | 0 | 48 | | var names = string.Join(", ", eventsWithoutHandler.Select(t => t.Name)); |
| | 0 | 49 | | throw new InvalidOperationException($"Webhook events without a registered IWebhookEventHandler<T>: {names}") |
| | | 50 | | } |
| | 0 | 51 | | } |
| | | 52 | | |
| | | 53 | | public static bool TryGetEventType(string type, out Type eventType) |
| | | 54 | | { |
| | 0 | 55 | | return _eventTypes.TryGetValue(type, out eventType!); |
| | | 56 | | } |
| | | 57 | | } |