1
0
Fork 1
mirror of https://github.com/TeamOctolings/Octobot.git synced 2025-04-20 00:43:36 +03:00
Octobot/src/Data/Options/TimeSpanOption.cs
Octol1ttle 74409174ce
Fix TimeSpan deserialization failing
Signed-off-by: Octol1ttle <l1ttleofficial@outlook.com>
2023-07-11 17:57:06 +05:00

28 lines
989 B
C#

using System.Text.Json.Nodes;
using Remora.Commands.Parsers;
using Remora.Results;
namespace Boyfriend.Data.Options;
public class TimeSpanOption : Option<TimeSpan> {
private static readonly TimeSpanParser Parser = new();
public TimeSpanOption(string name, TimeSpan defaultValue) : base(name, defaultValue) { }
public override TimeSpan Get(JsonNode settings) {
var property = settings[Name];
return property != null ? ParseTimeSpan(property.GetValue<string>()).Entity : DefaultValue;
}
public override Result Set(JsonNode settings, string from) {
if (!ParseTimeSpan(from).IsDefined(out var span))
return Result.FromError(new ArgumentInvalidError(nameof(from), Messages.InvalidSettingValue));
settings[Name] = span.ToString();
return Result.FromSuccess();
}
private static Result<TimeSpan> ParseTimeSpan(string from) {
return Parser.TryParseAsync(from).AsTask().GetAwaiter().GetResult();
}
}