diff --git a/src/NexusReader.Web.New/Services/NativeStorageService.cs b/src/NexusReader.Web.New/Services/NativeStorageService.cs new file mode 100644 index 0000000..e76603c --- /dev/null +++ b/src/NexusReader.Web.New/Services/NativeStorageService.cs @@ -0,0 +1,82 @@ +using FluentResults; +using Microsoft.JSInterop; +using NexusReader.Application.Abstractions.Services; + +namespace NexusReader.Web.New.Services; + +/// +/// Server-side implementation of INativeStorageService for Blazor Server. +/// Uses JS Interop to access browser local storage. +/// +public class NativeStorageService : INativeStorageService +{ + private readonly IJSRuntime _jsRuntime; + + public NativeStorageService(IJSRuntime jsRuntime) + { + _jsRuntime = jsRuntime; + } + + public async Task> GetSecureString(string key) + { + try + { + var value = await _jsRuntime.InvokeAsync("localStorage.getItem", key); + return Result.Ok(value ?? string.Empty); + } + catch (Exception ex) + { + return Result.Fail(new Error("Failed to read from local storage").CausedBy(ex)); + } + } + + public async Task SaveSecureString(string key, string value) + { + try + { + await _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, value); + return Result.Ok(); + } + catch (Exception ex) + { + return Result.Fail(new Error("Failed to write to local storage").CausedBy(ex)); + } + } + + public async Task> GetBool(string key) + { + var result = await GetSecureString(key); + if (result.IsFailed) return Result.Fail(result.Errors); + return Result.Ok(bool.TryParse(result.Value, out var val) && val); + } + + public async Task SaveBool(string key, bool value) + { + return await SaveSecureString(key, value.ToString().ToLower()); + } + + public async Task> GetInt(string key) + { + var result = await GetSecureString(key); + if (result.IsFailed) return Result.Fail(result.Errors); + return Result.Ok(int.TryParse(result.Value, out var val) ? val : 0); + } + + public async Task SaveInt(string key, int value) + { + return await SaveSecureString(key, value.ToString()); + } + + public async Task ClearAll() + { + try + { + await _jsRuntime.InvokeVoidAsync("localStorage.clear"); + return Result.Ok(); + } + catch (Exception ex) + { + return Result.Fail(new Error("Failed to clear local storage").CausedBy(ex)); + } + } +}