Skip to content

Commit 815d0a0

Browse files
committed
jsStorageService in base namespace
1 parent 9a9e560 commit 815d0a0

10 files changed

Lines changed: 85 additions & 68 deletions

File tree

README.md

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,18 @@ public static async Task Main(string[] args)
4848
```
4949

5050
## Usage (Blazor WebAssembly)
51-
example
51+
52+
### Parameters
53+
54+
| Parameter | Required | Description |
55+
|---------------------------|----------|------------------------------------------------------------------------------------------|
56+
| string cacheKey | Required | The key to use for the cache. |
57+
| Func<Task<TRes>> function | Required | The function to call. |
58+
| CachedRequest? request | Optional | settings for the cache request (explained below). |
59+
| TRes? defaultResponse | Optional | default value to return if the function failed or was not called and the cache is empty. |
60+
| CancellationToken clt | Optional | a cancellation token. |
61+
62+
### Example
5263

5364
```c#
5465
@inject Drogecode.Blazor.ExpireStorage.IExpireStorageService storageService
@@ -62,7 +73,7 @@ example
6273
async () => await apiClient.GetItemsAsync(),
6374
new CachedRequest{CachedAndReplace = true},
6475
new YourObjectResponse(),
65-
clt);
76+
cancellationToken);
6677
return response;
6778
}
6879

@@ -72,25 +83,30 @@ example
7283
## Options
7384

7485
### CachedRequest
86+
7587
You can give optional settings to the CachedRequest object.
7688

77-
* **OneCallPerLocalStorage** - If true, the result will be returned from localstorage if it is not expired. *Default: false*
78-
* **OneCallPerSession** - If true, the result will be returned from sessionstorage if it is not expired. *Default: false*
79-
* **ExpireLocalStorage** - The DateTime the localstorage value will be expired. *Default: 7 days.*
80-
* **ExpireSessionStorage** - The DateTime the sessionstorage value will be expired. *Default: 15 minutes.*
81-
* **IgnoreCache** - If true, never return a cached result. *Default: false*
82-
* **CachedAndReplace** - If true, The cached result will be returned and the cache will be refreshed for the next call. *Default: false*
83-
* **CacheWhenOffline** - If true, the cached result will be returned when offline, except when IgnoreCache is true. *Default: false*
84-
* **RetryOnJsonException** - If true, If a JSON exception occurs, the cache will be cleared and the request will be retried once. This will minimize the effect if a breaking change was introduced in the JSON value. *Default: true*
89+
| Parameter | Description | Default |
90+
|------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|
91+
| OneCallPerLocalStorage | If true, the result will be returned from localstorage if it is not expired. | false |
92+
| OneCallPerSession | If true, the result will be returned from sessionstorage if it is not expired. | false |
93+
| ExpireLocalStorage | The DateTime the localstorage value will be expired. | 7 days |
94+
| ExpireSessionStorage | The DateTime the sessionstorage value will be expired. | 15 minutes |
95+
| IgnoreCache | If true, never return a cached result. | false |
96+
| CachedAndReplace | If true, The cached result will be returned and the cache will be refreshed for the next call. If no cache is found, the default or NULL value will be returned. | false |
97+
| CacheWhenOffline | If true, the cached result will be returned when offline, except when IgnoreCache is true. | false |
98+
| RetryOnJsonException | If true, If a JSON exception occurs, the cache will be cleared and the request will be retried once. This will minimize the effect if a breaking change was introduced in the JSON value. | true |
8599

86100
### Global settings
87101

88102
#### Postfix
103+
89104
On, for example, MainLayout.razor.cs, you can set the Postfix to be used for all requests. This is useful if you have multiple users using the same app from the same browser.
90105

91106
`ExpireStorageService.Postfix = userId.ToString();`
92107

93108
#### IsOffline
109+
94110
ExpireStorageService knows two properties to monitor if the app is offline.
95111

96112
IsOffline is true when the last request had an `HttpRequestException`, after a successful request IsOffline will be false.
@@ -105,7 +121,8 @@ ExpireStorageService can log to the console if you want to see what is happening
105121

106122
### ICacheableResponse
107123

108-
If a response object implements ICacheableResponse, the HandledBy property will be set to `HandledBy.Cache` if the result was retrieved from cache and to `HandledBy.Default` if the default provided by the caller was used.
124+
If a response object implements ICacheableResponse, the HandledBy property will be set to `HandledBy.Cache` if the result was retrieved from cache and to `HandledBy.Default` if the default provided by
125+
the caller was used.
109126

110127
```c#
111128
using Drogecode.Blazor.ExpireStorage;

Src/Drogecode.Blazor.ExpireStorage/Drogecode.Blazor.ExpireStorage.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<Nullable>enable</Nullable>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<RootNamespace>Drogecode.Blazor.ExpireStorage</RootNamespace>
8-
<Version>1.0.0-rc1</Version>
8+
<Version>1.0.0-rc2</Version>
99
<Title>Drogecode.Blazor.ExpireStorage</Title>
1010
<Authors>Taco Droogers</Authors>
1111
<PackageProjectUrl>https://github.com/Drogecode/Drogecode.Blazor.ExpireStorage</PackageProjectUrl>

Src/Drogecode.Blazor.ExpireStorage/Enums/StorageLocation.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
namespace Drogecode.Blazor.ExpireStorage.Enums;
1+
namespace Drogecode.Blazor.ExpireStorage;
22

33
public enum StorageLocation
44
{
Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using Drogecode.Blazor.ExpireStorage.Interfaces;
2-
using Drogecode.Blazor.ExpireStorage.Services;
3-
using Microsoft.Extensions.DependencyInjection;
1+
using Microsoft.Extensions.DependencyInjection;
42
using Microsoft.Extensions.DependencyInjection.Extensions;
53

64
namespace Drogecode.Blazor.ExpireStorage;
@@ -12,7 +10,7 @@ public static IServiceCollection AddExpireStorage(this IServiceCollection servic
1210
services.TryAddScoped<ILocalStorageExpireService, LocalStorageExpireService>();
1311
services.TryAddScoped<ISessionExpireService, SessionExpireService>();
1412
services.TryAddScoped<IExpireStorageService, ExpireStorageService>();
15-
services.TryAddScoped<IExpireStorageJsService, ExpireStorageJsService>();
13+
services.TryAddScoped<IJsStorageService, JsStorageService>();
1614
return services;
1715
}
1816

@@ -21,7 +19,7 @@ public static IServiceCollection AddExpireStorageAsSingleton(this IServiceCollec
2119
services.TryAddSingleton<ILocalStorageExpireService, LocalStorageExpireService>();
2220
services.TryAddSingleton<ISessionExpireService, SessionExpireService>();
2321
services.TryAddSingleton<IExpireStorageService, ExpireStorageService>();
24-
services.TryAddSingleton<IExpireStorageJsService, ExpireStorageJsService>();
22+
services.TryAddSingleton<IJsStorageService, JsStorageService>();
2523
return services;
2624
}
2725
}

Src/Drogecode.Blazor.ExpireStorage/Interfaces/IExpireStorageJsService.cs renamed to Src/Drogecode.Blazor.ExpireStorage/Interfaces/IJsStorageService.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
using Drogecode.Blazor.ExpireStorage.Enums;
1+
namespace Drogecode.Blazor.ExpireStorage;
22

3-
namespace Drogecode.Blazor.ExpireStorage.Interfaces;
4-
5-
public interface IExpireStorageJsService
3+
public interface IJsStorageService
64
{
7-
T RetrieveItem<T>(string storageKey, StorageLocation storage, T defaultIfNull) where T : notnull;
8-
Task StoreItem<T>(string storageKey, StorageLocation storageLocation, T itemToStore) where T : notnull;
5+
T RetrieveItem<T>(string storageKey, StorageLocation storage, T defaultIfNull);
6+
Task StoreItem<T>(string storageKey, StorageLocation storageLocation, T itemToStore);
97
Task<T?> RetrieveItem<T>(string storageKey, StorageLocation storageLocation);
108
Task RemoveItem(string storageKey, StorageLocation storageLocation);
119
}

Src/Drogecode.Blazor.ExpireStorage/Services/ExpireStorageJsService.cs renamed to Src/Drogecode.Blazor.ExpireStorage/Services/JsStorageService.cs

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,20 @@
11
using System.Text;
22
using System.Text.Json;
3-
using Drogecode.Blazor.ExpireStorage.Enums;
4-
using Drogecode.Blazor.ExpireStorage.Helpers;
5-
using Drogecode.Blazor.ExpireStorage.Interfaces;
63
using Microsoft.JSInterop;
74

8-
namespace Drogecode.Blazor.ExpireStorage.Services;
5+
namespace Drogecode.Blazor.ExpireStorage;
96

10-
internal class ExpireStorageJsService : IExpireStorageJsService
7+
internal class JsStorageService : IJsStorageService
118
{
129
private readonly IJSRuntime _jsRuntime;
1310
private readonly Dictionary<string, string> _pageCache = new();
1411

15-
public ExpireStorageJsService(IJSRuntime jsRuntime)
12+
public JsStorageService(IJSRuntime jsRuntime)
1613
{
1714
_jsRuntime = jsRuntime;
1815
}
1916

20-
public T RetrieveItem<T>(string storageKey, StorageLocation storage, T defaultIfNull) where T : notnull
17+
public T RetrieveItem<T>(string storageKey, StorageLocation storage, T defaultIfNull)
2118
{
2219
var base64String = storage switch
2320
{
@@ -34,7 +31,7 @@ public T RetrieveItem<T>(string storageKey, StorageLocation storage, T defaultIf
3431
return JsonSerializer.Deserialize<T>(jsonString) ?? defaultIfNull;
3532
}
3633

37-
public async Task StoreItem<T>(string storageKey, StorageLocation storageLocation, T itemToStore) where T : notnull
34+
public async Task StoreItem<T>(string storageKey, StorageLocation storageLocation, T itemToStore)
3835
{
3936
var utf8Byes = JsonSerializer.SerializeToUtf8Bytes<T>(itemToStore);
4037
var base64String = Convert.ToBase64String(utf8Byes);
@@ -61,9 +58,6 @@ public async Task StoreItem<T>(string storageKey, StorageLocation storageLocatio
6158
StorageLocation.BrowserSession => await _jsRuntime.InvokeAsync<string?>("sessionStorage.getItem", storageKey) ?? string.Empty,
6259
_ => _pageCache.TryGetValue(storageKey, out string? cachedItem) ? cachedItem : string.Empty
6360
};
64-
65-
ConsoleHelper.WriteLine($"base64String: {base64String}");
66-
6761
if (string.IsNullOrEmpty(base64String)) return default;
6862
var utf8Byes = Convert.FromBase64String(base64String);
6963
var jsonString = Encoding.UTF8.GetString(utf8Byes);

Src/Drogecode.Blazor.ExpireStorage/Services/LocalStorageExpireService.cs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,21 @@
11
using System.Buffers.Text;
22
using System.Text;
33
using System.Text.Json;
4-
using Drogecode.Blazor.ExpireStorage.Enums;
54
using Drogecode.Blazor.ExpireStorage.Helpers;
6-
using Drogecode.Blazor.ExpireStorage.Interfaces;
75
using Drogecode.Blazor.ExpireStorage.Models;
86
using Microsoft.JSInterop;
97

108
namespace Drogecode.Blazor.ExpireStorage;
119

1210
public class LocalStorageExpireService : ILocalStorageExpireService
1311
{
14-
private readonly IExpireStorageJsService _expireStorageJsService;
12+
private readonly IJsStorageService _jsStorageService;
1513
private readonly IJSRuntime _jsRuntime;
1614
private Lazy<IJSObjectReference> _accessorJsRef = new();
1715

18-
public LocalStorageExpireService(IExpireStorageJsService expireStorageJsService, IJSRuntime jsRuntime)
16+
public LocalStorageExpireService(IJsStorageService jsStorageService, IJSRuntime jsRuntime)
1917
{
20-
_expireStorageJsService = expireStorageJsService;
18+
_jsStorageService = jsStorageService;
2119
_jsRuntime = jsRuntime;
2220

2321
//Fire and forget
@@ -80,7 +78,7 @@ private async Task DeleteExpiredCache()
8078

8179
if (expiryStorageModel.Ttl >= ttl) continue;
8280
ConsoleHelper.WriteLine($"localstorage deleting {package.Key}, expired {new DateTime(expiryStorageModel.Ttl)}");
83-
await _expireStorageJsService.RemoveItem(package.Key, StorageLocation.BrowserLocal);
81+
await _jsStorageService.RemoveItem(package.Key, StorageLocation.BrowserLocal);
8482
count++;
8583
}
8684

@@ -101,13 +99,13 @@ private async Task DeleteExpiredCache()
10199

102100
public async ValueTask<T?> GetItemAsync<T>(string key, CancellationToken cancellationToken = default)
103101
{
104-
var value = await _expireStorageJsService.RetrieveItem<ExpiryStorageModel<T?>>(key, StorageLocation.BrowserLocal);
102+
var value = await _jsStorageService.RetrieveItem<ExpiryStorageModel<T?>>(key, StorageLocation.BrowserLocal);
105103
if (value is null || value.Data is null)
106104
return default(T);
107105
if (value.Ttl < DateTime.UtcNow.Ticks)
108106
{
109107
ConsoleHelper.WriteLine($"localstorage deleting {key}, expired {new DateTime(value.Ttl)} on trying to get");
110-
await _expireStorageJsService.RemoveItem(key, StorageLocation.BrowserLocal);
108+
await _jsStorageService.RemoveItem(key, StorageLocation.BrowserLocal);
111109
return default(T);
112110
}
113111

@@ -122,11 +120,11 @@ public async ValueTask SetItemAsync<T>(string key, T data, DateTime expire, Canc
122120
Data = data,
123121
Ttl = expire.Ticks,
124122
};
125-
await _expireStorageJsService.StoreItem(key, StorageLocation.BrowserLocal, value);
123+
await _jsStorageService.StoreItem(key, StorageLocation.BrowserLocal, value);
126124
}
127125

128126
public async Task DeleteItemAsync(string key, CancellationToken clt)
129127
{
130-
await _expireStorageJsService.RemoveItem(key, StorageLocation.BrowserLocal);
128+
await _jsStorageService.RemoveItem(key, StorageLocation.BrowserLocal);
131129
}
132130
}
Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
1-
using Drogecode.Blazor.ExpireStorage.Enums;
2-
using Drogecode.Blazor.ExpireStorage.Interfaces;
3-
using Drogecode.Blazor.ExpireStorage.Models;
1+
using Drogecode.Blazor.ExpireStorage.Models;
42

53
namespace Drogecode.Blazor.ExpireStorage;
64

75
public class SessionExpireService : ISessionExpireService
86
{
9-
private readonly IExpireStorageJsService _expireStorageJsService;
7+
private readonly IJsStorageService _jsStorageService;
108

11-
public SessionExpireService(IExpireStorageJsService expireStorageJsService)
9+
public SessionExpireService(IJsStorageService jsStorageService)
1210
{
13-
_expireStorageJsService = expireStorageJsService;
11+
_jsStorageService = jsStorageService;
1412
}
1513

1614
public async ValueTask<T?> GetItemAsync<T>(string key, CancellationToken clt = default)
1715
{
18-
var value = await _expireStorageJsService.RetrieveItem<ExpiryStorageModel<T?>>(key, StorageLocation.BrowserSession);
16+
var value = await _jsStorageService.RetrieveItem<ExpiryStorageModel<T?>>(key, StorageLocation.BrowserSession);
1917
var ttl = DateTime.UtcNow.Ticks;
2018
if (value is null || value.Data is null || value.Ttl <= ttl) return default;
2119
var result = value.Data;
@@ -29,6 +27,6 @@ public async ValueTask SetItemAsync<T>(string key, T data, DateTime expire, Canc
2927
Data = data,
3028
Ttl = expire.Ticks
3129
};
32-
await _expireStorageJsService.StoreItem(key, StorageLocation.BrowserSession, value);
30+
await _jsStorageService.StoreItem(key, StorageLocation.BrowserSession, value);
3331
}
3432
}

Tests/Drogecode.Blazor.ExpireStorage.Tests/Mocks/MockExpireStorageJsService.cs renamed to Tests/Drogecode.Blazor.ExpireStorage.Tests/Mocks/MockJsStorageService.cs

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,59 @@
1-
using Drogecode.Blazor.ExpireStorage.Enums;
2-
using Drogecode.Blazor.ExpireStorage.Interfaces;
31
using Microsoft.Extensions.Caching.Memory;
42

53
namespace Drogecode.Blazor.ExpireStorage.Tests.Mocks;
64

7-
public class MockExpireStorageJsService : IExpireStorageJsService
5+
public class MockJsStorageService : IJsStorageService
86
{
97
private readonly IMemoryCache _memoryCache;
10-
public MockExpireStorageJsService(IMemoryCache memoryCache)
8+
9+
public MockJsStorageService(IMemoryCache memoryCache)
1110
{
1211
_memoryCache = memoryCache;
1312
}
14-
15-
public T RetrieveItem<T>(string storageKey, StorageLocation storage, T defaultIfNull) where T : notnull
13+
14+
public T RetrieveItem<T>(string storageKey, StorageLocation storageLocation, T defaultIfNull) where T : notnull
1615
{
17-
if (_memoryCache.TryGetValue(storageKey, out object? value))
16+
if (_memoryCache.TryGetValue(storageKey + storageLocation, out object? value))
1817
{
1918
if (value is null) return defaultIfNull;
20-
try { return (T)value; } catch { return defaultIfNull; }
19+
try
20+
{
21+
return (T)value;
22+
}
23+
catch
24+
{
25+
return defaultIfNull;
26+
}
2127
}
28+
2229
return defaultIfNull;
2330
}
2431

2532
public async Task StoreItem<T>(string storageKey, StorageLocation storageLocation, T itemToStore) where T : notnull
2633
{
27-
_memoryCache.Set(storageKey, itemToStore);
34+
_memoryCache.Set(storageKey + storageLocation, itemToStore);
2835
}
2936

3037
public async Task<T?> RetrieveItem<T>(string storageKey, StorageLocation storageLocation)
3138
{
32-
if (_memoryCache.TryGetValue(storageKey, out object? value))
39+
if (_memoryCache.TryGetValue(storageKey + storageLocation, out object? value))
3340
{
3441
if (value is null) return default;
35-
try { return (T)value; } catch { return default; }
42+
try
43+
{
44+
return (T)value;
45+
}
46+
catch
47+
{
48+
return default;
49+
}
3650
}
51+
3752
return default;
3853
}
3954

4055
public async Task RemoveItem(string storageKey, StorageLocation storageLocation)
4156
{
42-
_memoryCache.Remove(storageKey);
57+
_memoryCache.Remove(storageKey + storageLocation);
4358
}
4459
}

Tests/Drogecode.Blazor.ExpireStorage.Tests/Startup.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using Drogecode.Blazor.ExpireStorage.Interfaces;
2-
using Drogecode.Blazor.ExpireStorage.Tests.Mocks;
1+
using Drogecode.Blazor.ExpireStorage.Tests.Mocks;
32
using Microsoft.Extensions.DependencyInjection;
43
using Microsoft.JSInterop;
54
using Xunit.DependencyInjection.Logging;
@@ -16,7 +15,7 @@ public void ConfigureServices(IServiceCollection services)
1615
services.AddScoped<IExpireStorageService, ExpireStorageService>();
1716

1817
services.AddScoped<IJSRuntime, JSRuntimeMock>();
19-
services.AddScoped<IExpireStorageJsService, MockExpireStorageJsService>();
18+
services.AddScoped<IJsStorageService, MockJsStorageService>();
2019

2120
services.AddLogging(lb => lb.AddXunitOutput());
2221
}

0 commit comments

Comments
 (0)