using System;
using System.Collections.Generic;
using Svrnty.CQRS.Events.Abstractions.Sagas;
namespace Svrnty.CQRS.Events.Sagas;
///
/// In-memory implementation of saga data storage.
///
public sealed class SagaData : ISagaData
{
private readonly Dictionary _data = new();
///
public T? Get(string key)
{
if (_data.TryGetValue(key, out var value))
{
if (value is T typedValue)
return typedValue;
// Attempt conversion
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
return default;
}
}
return default;
}
///
public void Set(string key, T value)
{
if (value == null)
{
_data.Remove(key);
}
else
{
_data[key] = value;
}
}
///
public bool Contains(string key)
{
return _data.ContainsKey(key);
}
///
public IDictionary GetAll()
{
return new Dictionary(_data);
}
///
/// Load data from dictionary.
///
public void LoadFrom(IDictionary data)
{
_data.Clear();
foreach (var kvp in data)
{
_data[kvp.Key] = kvp.Value;
}
}
}