| | | 1 | | using System.Text.Json; |
| | | 2 | | using Syki.Back.Converters; |
| | | 3 | | using Syki.Back.Domain.Webhooks; |
| | | 4 | | |
| | | 5 | | namespace Syki.Back.Webhooks; |
| | | 6 | | |
| | | 7 | | public interface IWebhookEvent; |
| | | 8 | | |
| | | 9 | | public interface IWebhookEventHandler<T> where T : IWebhookEvent |
| | | 10 | | { |
| | | 11 | | Task Handle(ReceivedWebhookEvent evt, T data); |
| | | 12 | | } |
| | | 13 | | |
| | | 14 | | public interface IWebhookEventInvoker |
| | | 15 | | { |
| | | 16 | | Task Invoke(IServiceProvider sp, ReceivedWebhookEvent evt); |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | public class WebhookEventInvoker<T> : IWebhookEventInvoker where T : IWebhookEvent |
| | | 20 | | { |
| | 0 | 21 | | private static readonly JsonSerializerOptions _options = new() |
| | 0 | 22 | | { |
| | 0 | 23 | | PropertyNameCaseInsensitive = true, |
| | 0 | 24 | | Converters = { new SykiStringEnumConverter() }, |
| | 0 | 25 | | }; |
| | | 26 | | |
| | | 27 | | public async Task Invoke(IServiceProvider sp, ReceivedWebhookEvent evt) |
| | | 28 | | { |
| | 0 | 29 | | var data = JsonSerializer.Deserialize<T>(evt.Payload, _options)!; |
| | 0 | 30 | | var handler = sp.GetRequiredService<IWebhookEventHandler<T>>(); |
| | 0 | 31 | | await handler.Handle(evt, data); |
| | 0 | 32 | | } |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | [AttributeUsage(AttributeTargets.Class)] |
| | | 36 | | public class WebhookEventTypeAttribute(string type) : Attribute |
| | | 37 | | { |
| | | 38 | | public string Type { get; } = type; |
| | | 39 | | } |