Add Nullable ComponentTypeConverter and TypeReader (#2307)

* add nullable ComponentTypeConverter and TypeReader

* add converter and reader to interactionservice
This commit is contained in:
Cenk Ergen
2022-05-18 10:45:18 +03:00
committed by GitHub
parent b333de2237
commit 6fbd396832
3 changed files with 50 additions and 2 deletions

View File

@@ -223,7 +223,8 @@ namespace Discord.Interactions
new ConcurrentDictionary<Type, Type>
{
[typeof(Array)] = typeof(DefaultArrayComponentConverter<>),
[typeof(IConvertible)] = typeof(DefaultValueComponentConverter<>)
[typeof(IConvertible)] = typeof(DefaultValueComponentConverter<>),
[typeof(Nullable<>)] = typeof(NullableComponentConverter<>)
});
_typeReaderMap = new TypeMap<TypeReader, string>(this, new ConcurrentDictionary<Type, TypeReader>(),
@@ -234,7 +235,8 @@ namespace Discord.Interactions
[typeof(IUser)] = typeof(DefaultUserReader<>),
[typeof(IMessage)] = typeof(DefaultMessageReader<>),
[typeof(IConvertible)] = typeof(DefaultValueReader<>),
[typeof(Enum)] = typeof(EnumReader<>)
[typeof(Enum)] = typeof(EnumReader<>),
[typeof(Nullable<>)] = typeof(NullableReader<>)
});
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Threading.Tasks;
namespace Discord.Interactions
{
internal class NullableComponentConverter<T> : ComponentTypeConverter<T>
{
private readonly ComponentTypeConverter _typeConverter;
public NullableComponentConverter(InteractionService interactionService, IServiceProvider services)
{
var type = Nullable.GetUnderlyingType(typeof(T));
if (type is null)
throw new ArgumentException($"No type {nameof(TypeConverter)} is defined for this {type.FullName}", "type");
_typeConverter = interactionService.GetComponentTypeConverter(type, services);
}
public override Task<TypeConverterResult> ReadAsync(IInteractionContext context, IComponentInteractionData option, IServiceProvider services)
=> string.IsNullOrEmpty(option.Value) ? Task.FromResult(TypeConverterResult.FromSuccess(null)) : _typeConverter.ReadAsync(context, option, services);
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Threading.Tasks;
namespace Discord.Interactions
{
internal class NullableReader<T> : TypeReader<T>
{
private readonly TypeReader _typeReader;
public NullableReader(InteractionService interactionService, IServiceProvider services)
{
var type = Nullable.GetUnderlyingType(typeof(T));
if (type is null)
throw new ArgumentException($"No type {nameof(TypeConverter)} is defined for this {type.FullName}", "type");
_typeReader = interactionService.GetTypeReader(type, services);
}
public override Task<TypeConverterResult> ReadAsync(IInteractionContext context, string option, IServiceProvider services)
=> string.IsNullOrEmpty(option) ? Task.FromResult(TypeConverterResult.FromSuccess(null)) : _typeReader.ReadAsync(context, option, services);
}
}