mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
Initial KV API concept
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user