-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathLocalStorageService.cs
More file actions
57 lines (51 loc) · 1.62 KB
/
Copy pathLocalStorageService.cs
File metadata and controls
57 lines (51 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
namespace LinkDotNet.Blog.Web.Features.Services;
public sealed class LocalStorageService : ILocalStorageService
{
private readonly ProtectedLocalStorage localStorage;
public LocalStorageService(ProtectedLocalStorage localStorage)
{
this.localStorage = localStorage;
}
public async ValueTask<bool> ContainsKeyAsync(string key)
{
try
{
return (await localStorage.GetAsync<object>(key)).Success;
}
catch (CryptographicException)
{
await localStorage.DeleteAsync(key);
return false;
}
}
public async ValueTask<T> GetItemAsync<T>(string key)
{
try
{
var result = await localStorage.GetAsync<T>(key);
return !result.Success ? throw new KeyNotFoundException($"Key {key} not found") : result.Value!;
}
catch (CryptographicException)
{
await localStorage.DeleteAsync(key);
throw new KeyNotFoundException($"Key {key} was invalid and has been removed");
}
}
public async ValueTask SetItemAsync<T>(string key, T value)
{
try
{
await localStorage.SetAsync(key, value!);
}
catch (CryptographicException)
{
await localStorage.DeleteAsync(key);
throw new InvalidOperationException($"Could not set value for key {key}. The key has been removed.");
}
}
}