Initial KV API concept

This commit is contained in:
Kruzya
2023-01-05 08:01:18 +03:00
parent a97fac85e4
commit 984e582ce4
8 changed files with 207 additions and 0 deletions
+53
View File
@@ -0,0 +1,53 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Kruzya.TelegramBot.Core.Option;
public class OptionItem<T> : IOptionItem<T>
{
public IOptionKey Key { get; }
public T Value
{
get => _value;
set
{
_value = value;
_isChanged = true;
}
}
public bool IsChanged => _isChanged;
private T _value;
private bool _isChanged;
public OptionItem(IOptionKey key, T value)
{
Key = key;
Value = value;
}
public async Task LoadAsync(IOptionStorageAdapter adapter)
{
var savedValue = await adapter.LoadValueAsync(Key);
if (savedValue == null)
{
return;
}
// This property changed when we're loaded default value. Reset here.
_isChanged = false;
_value = JsonSerializer.Deserialize<T>(new ReadOnlySpan<byte>(savedValue));
}
public async Task SaveAsync(IOptionStorageAdapter adapter)
{
var data = JsonSerializer.SerializeToUtf8Bytes(Value, new JsonSerializerOptions { WriteIndented = false,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
await adapter.SaveValueAsync(Key, data);
}
}