WasmTextFileStore.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Microsoft.JSInterop;
  2. using RackPeek.Domain.Persistence.Yaml;
  3. namespace RackPeek.Web.Viewer;
  4. public sealed class WasmTextFileStore(
  5. IJSRuntime js,
  6. HttpClient http) : ITextFileStore {
  7. private const string _prefix = "rackpeek:file:";
  8. public async Task<bool> ExistsAsync(string path) {
  9. var value = await js.InvokeAsync<string?>(
  10. "rackpeekStorage.get",
  11. Key(path));
  12. return !string.IsNullOrWhiteSpace(value);
  13. }
  14. public async Task<string> ReadAllTextAsync(string path) {
  15. Console.WriteLine($"WASM store read: {path}");
  16. var value = await js.InvokeAsync<string?>(
  17. "rackpeekStorage.get",
  18. Key(path));
  19. if (!string.IsNullOrWhiteSpace(value)) {
  20. Console.WriteLine("Loaded from browser storage");
  21. return value;
  22. }
  23. Console.WriteLine("Storage empty — loading from wwwroot via HTTP");
  24. try {
  25. var result = await http.GetStringAsync(path);
  26. Console.WriteLine($"Loaded {result.Length} chars from HTTP");
  27. // optional auto-persist bootstrap
  28. if (!string.IsNullOrWhiteSpace(result))
  29. await WriteAllTextAsync(path, result);
  30. return result;
  31. }
  32. catch (Exception ex) {
  33. Console.WriteLine("HTTP load failed: " + ex.Message);
  34. throw; // TEMP — don't swallow during debug
  35. }
  36. }
  37. public async Task WriteAllTextAsync(string path, string contents) {
  38. await js.InvokeVoidAsync(
  39. "rackpeekStorage.set",
  40. Key(path),
  41. contents);
  42. }
  43. private static string Key(string path) => _prefix + path;
  44. }