squash a bunch of commits
This commit is contained in:
51
Shogi.UI/Shared/LocalStorage.cs
Normal file
51
Shogi.UI/Shared/LocalStorage.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using Microsoft.JSInterop;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Shogi.UI.Shared
|
||||
{
|
||||
public class LocalStorage : ILocalStorage
|
||||
{
|
||||
private readonly JsonSerializerOptions jsonOptions;
|
||||
private readonly IJSRuntime jSRuntime;
|
||||
|
||||
public LocalStorage(IJSRuntime jSRuntime)
|
||||
{
|
||||
jsonOptions = new JsonSerializerOptions();
|
||||
jsonOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
this.jSRuntime = jSRuntime;
|
||||
}
|
||||
|
||||
public ValueTask Set<T>(string key, T value)
|
||||
{
|
||||
var serialized = JsonSerializer.Serialize(value);
|
||||
return jSRuntime.InvokeVoidAsync("localStorage.setItem", key, serialized);
|
||||
}
|
||||
|
||||
public async ValueTask<T?> Get<T>(string key) where T : struct
|
||||
{
|
||||
|
||||
var value = await jSRuntime.InvokeAsync<string>("localStorage.getItem", key);
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<T>(value, jsonOptions);
|
||||
}
|
||||
catch (ArgumentNullException)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask Delete(string key)
|
||||
{
|
||||
return jSRuntime.InvokeVoidAsync("localStorage.removeItem", key);
|
||||
}
|
||||
}
|
||||
|
||||
public interface ILocalStorage
|
||||
{
|
||||
ValueTask Delete(string key);
|
||||
ValueTask<T?> Get<T>(string key) where T : struct;
|
||||
ValueTask Set<T>(string key, T value);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user