Files
mapo-core/MP.Data/Services/LocalStorageService.cs

88 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using Microsoft.JSInterop;
namespace MP.Data.Services
{
public interface ILocalStorageService
{
#region Public Methods
Task ClearAsync();
Task<bool> ContainKeyAsync(string key);
Task<T?> GetItemAsync<T>(string key);
Task<T> GetItemAsync<T>(string key, T fallback);
Task RemoveItemAsync(string key);
Task SetItemAsync<T>(string key, T value);
#endregion Public Methods
}
public class LocalStorageService : ILocalStorageService
{
#region Public Constructors
public LocalStorageService(IJSRuntime js)
{
_js = js;
}
#endregion Public Constructors
#region Public Methods
public async Task ClearAsync()
{
await _js.InvokeVoidAsync("localStorage.clear");
}
public async Task<bool> ContainKeyAsync(string key)
{
var value = await _js.InvokeAsync<string>("localStorage.getItem", key);
return value != null;
}
public async Task<T?> GetItemAsync<T>(string key)
{
var json = await _js.InvokeAsync<string>("localStorage.getItem", key);
if (json is null)
return default;
return JsonSerializer.Deserialize<T>(json);
}
public async Task<T> GetItemAsync<T>(string key, T fallback)
{
var json = await _js.InvokeAsync<string>("localStorage.getItem", key);
if (json is null)
return fallback;
return JsonSerializer.Deserialize<T>(json) ?? fallback;
}
public async Task RemoveItemAsync(string key)
{
await _js.InvokeVoidAsync("localStorage.removeItem", key);
}
public async Task SetItemAsync<T>(string key, T value)
{
var json = JsonSerializer.Serialize(value);
await _js.InvokeVoidAsync("localStorage.setItem", key, json);
}
#endregion Public Methods
#region Private Fields
private readonly IJSRuntime _js;
#endregion Private Fields
}
}