| | | 1 | | using System.Text.Json; |
| | | 2 | | using Syki.Back.Converters; |
| | | 3 | | |
| | | 4 | | namespace Syki.Back.Commands; |
| | | 5 | | |
| | | 6 | | public interface ICommandHandler<T> where T : ICommand |
| | | 7 | | { |
| | | 8 | | Task Handle(int commandId, T command); |
| | | 9 | | } |
| | | 10 | | |
| | | 11 | | public interface ICommandInvoker |
| | | 12 | | { |
| | | 13 | | Task Invoke(IServiceProvider sp, int commandId, string json); |
| | | 14 | | object Deserialize(string json); |
| | | 15 | | } |
| | | 16 | | |
| | | 17 | | public class CommandInvoker<T> : ICommandInvoker where T : ICommand |
| | | 18 | | { |
| | 4 | 19 | | private static readonly JsonSerializerOptions _options = new() |
| | 4 | 20 | | { |
| | 4 | 21 | | PropertyNameCaseInsensitive = true, |
| | 4 | 22 | | Converters = { new SykiStringEnumConverter() }, |
| | 4 | 23 | | }; |
| | | 24 | | |
| | | 25 | | public async Task Invoke(IServiceProvider sp, int commandId, string json) |
| | | 26 | | { |
| | 304 | 27 | | var data = JsonSerializer.Deserialize<T>(json, _options)!; |
| | 304 | 28 | | var handler = sp.GetRequiredService<ICommandHandler<T>>(); |
| | 304 | 29 | | await handler.Handle(commandId, data); |
| | 304 | 30 | | } |
| | | 31 | | |
| | | 32 | | public object Deserialize(string json) |
| | | 33 | | { |
| | 0 | 34 | | return JsonSerializer.Deserialize<T>(json, _options)!; |
| | | 35 | | } |
| | | 36 | | } |