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 ContainKeyAsync(string key); Task GetItemAsync(string key); Task GetItemAsync(string key, T fallback); Task RemoveItemAsync(string key); Task SetItemAsync(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 ContainKeyAsync(string key) { var value = await _js.InvokeAsync("localStorage.getItem", key); return value != null; } public async Task GetItemAsync(string key) { var json = await _js.InvokeAsync("localStorage.getItem", key); if (json is null) return default; return JsonSerializer.Deserialize(json); } public async Task GetItemAsync(string key, T fallback) { var json = await _js.InvokeAsync("localStorage.getItem", key); if (json is null) return fallback; return JsonSerializer.Deserialize(json) ?? fallback; } public async Task RemoveItemAsync(string key) { await _js.InvokeVoidAsync("localStorage.removeItem", key); } public async Task SetItemAsync(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 } }