| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using TeleFlow.Telegram.Schema.Abstractions; |
| | | 5 | | |
| | | 6 | | namespace TeleFlow.Telegram.Internal; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Adapts a generated schema method object to the executable request contract used by the Telegram client runtime. |
| | | 10 | | /// It resolves the generated method name and maps a parsed Telegram result element into the strongly typed method resul |
| | | 11 | | /// </summary> |
| | | 12 | | internal sealed class SchemaTelegramRequest<TResult> : |
| | | 13 | | ITelegramExecutableRequest<TelegramRequestResult<TResult>> |
| | | 14 | | { |
| | 6 | 15 | | private static readonly ConcurrentDictionary<Type, string> MethodNameCache = []; |
| | | 16 | | private readonly ITelegramApiMethod<TResult> _method; |
| | | 17 | | |
| | | 18 | | public SchemaTelegramRequest(ITelegramApiMethod<TResult> method) |
| | | 19 | | { |
| | 85 | 20 | | ArgumentNullException.ThrowIfNull(method); |
| | 85 | 21 | | _method = method; |
| | 85 | 22 | | } |
| | | 23 | | |
| | 269 | 24 | | public string MethodName => MethodNameCache.GetOrAdd(_method.GetType(), ResolveMethodName); |
| | | 25 | | |
| | 92 | 26 | | public object Payload => _method; |
| | | 27 | | |
| | | 28 | | public TelegramRequestResult<TResult> DeserializeResponse( |
| | | 29 | | JsonSerializerOptions serializerOptions, |
| | | 30 | | JsonElement result) |
| | | 31 | | { |
| | 54 | 32 | | ArgumentNullException.ThrowIfNull(serializerOptions); |
| | | 33 | | |
| | 54 | 34 | | var value = result.Deserialize<TResult>(serializerOptions); |
| | | 35 | | |
| | 53 | 36 | | if (value is null) |
| | | 37 | | { |
| | 0 | 38 | | throw new TelegramRequestException( |
| | 0 | 39 | | $"Telegram response for method '{MethodName}' did not contain a deserializable result payload."); |
| | | 40 | | } |
| | | 41 | | |
| | 53 | 42 | | return new TelegramRequestResult<TResult>(value); |
| | | 43 | | } |
| | | 44 | | |
| | | 45 | | private static string ResolveMethodName(Type methodType) |
| | | 46 | | { |
| | 9 | 47 | | var property = methodType.GetProperty( |
| | 9 | 48 | | "MethodName", |
| | 9 | 49 | | BindingFlags.Public | BindingFlags.Static); |
| | | 50 | | |
| | 9 | 51 | | if (property?.GetValue(null) is string methodName && !string.IsNullOrWhiteSpace(methodName)) |
| | | 52 | | { |
| | 9 | 53 | | return methodName; |
| | | 54 | | } |
| | | 55 | | |
| | 0 | 56 | | throw new InvalidOperationException( |
| | 0 | 57 | | $"Telegram schema method type '{methodType.FullName}' does not expose a public static MethodName property.") |
| | | 58 | | } |
| | | 59 | | } |