This commit is contained in:
54
BotPages.Core/Pages/StatefullPage.cs
Normal file
54
BotPages.Core/Pages/StatefullPage.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace BotPages.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Базовый класс страницы с состоянием и аргументами.
|
||||
/// </summary>
|
||||
public abstract class StatefullPage<TArgs> : StatefullPage
|
||||
{
|
||||
/// <summary>Вход на страницу с аргументами.</summary>
|
||||
public virtual Task OnEnter(PageContext ctx, TArgs args, CancellationToken ct)
|
||||
=> base.OnEnter(ctx, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Базовый класс страницы с состоянием.
|
||||
/// Создается для каждого пользователя.
|
||||
/// </summary>
|
||||
public abstract class StatefullPage : Page
|
||||
{
|
||||
/// <summary>
|
||||
/// Загружает значения свойств из StateStorage.
|
||||
/// </summary>
|
||||
internal async Task LoadState(PageContext ctx, CancellationToken ct)
|
||||
{
|
||||
foreach (var prop in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
var attr = prop.GetCustomAttribute<StatefullAttribute>();
|
||||
if (attr is null) continue;
|
||||
|
||||
var value = await ctx.StateStorage.GetAsync<object>(ctx.SessionKey, attr.Key, ct);
|
||||
|
||||
if (value is not null)
|
||||
{
|
||||
prop.SetValue(this, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохраняет значения свойств в StateStorage.
|
||||
/// </summary>
|
||||
internal async Task SaveState(PageContext ctx, CancellationToken ct)
|
||||
{
|
||||
foreach (var prop in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
var attr = prop.GetCustomAttribute<StatefullAttribute>();
|
||||
if (attr is null) continue;
|
||||
|
||||
var value = prop.GetValue(this);
|
||||
await ctx.StateStorage.SetAsync(ctx.SessionKey, attr.Key, value, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user