WasmTextFileStore.cs 1.7 KB

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