|
| 1 | +using System; |
| 2 | +using System.Threading.Tasks; |
| 3 | +using Blazor.Extensions.Storage.Interfaces; |
| 4 | +using Microsoft.JSInterop; |
| 5 | + |
| 6 | +namespace Blazor.Extensions.Storage |
| 7 | +{ |
| 8 | + internal abstract class Storage : IStorage |
| 9 | + { |
| 10 | + private readonly IJSRuntime runtime; |
| 11 | + private readonly string storageName; |
| 12 | + |
| 13 | + protected Storage(IJSRuntime runtime, string storageName) |
| 14 | + { |
| 15 | + this.runtime = runtime; |
| 16 | + this.storageName = storageName; |
| 17 | + } |
| 18 | + |
| 19 | + public ValueTask<int> Length() => this.runtime.InvokeAsync<int>(MethodNames.LENGTH_METHOD, this.storageName); |
| 20 | + |
| 21 | + public ValueTask Clear() => this.runtime.InvokeVoidAsync(MethodNames.CLEAR_METHOD, this.storageName); |
| 22 | + |
| 23 | + public ValueTask<TItem> GetItem<TItem>(string key) |
| 24 | + { |
| 25 | + if(string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); |
| 26 | + |
| 27 | + return this.runtime.InvokeAsync<TItem>(MethodNames.GET_ITEM_METHOD, this.storageName, key); |
| 28 | + } |
| 29 | + |
| 30 | + public ValueTask<string> Key(int index) => this.runtime.InvokeAsync<string>(MethodNames.KEY_METHOD, this.storageName, index); |
| 31 | + |
| 32 | + public ValueTask RemoveItem(string key) |
| 33 | + { |
| 34 | + if(string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); |
| 35 | + |
| 36 | + return this.runtime.InvokeVoidAsync(MethodNames.REMOVE_ITEM_METHOD, this.storageName, key); |
| 37 | + } |
| 38 | + |
| 39 | + public ValueTask SetItem<TItem>(string key, TItem item) |
| 40 | + { |
| 41 | + if(string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); |
| 42 | + |
| 43 | + return this.runtime.InvokeVoidAsync(MethodNames.SET_ITEM_METHOD, this.storageName, key, item); |
| 44 | + } |
| 45 | + |
| 46 | + private class MethodNames |
| 47 | + { |
| 48 | + public const string LENGTH_METHOD = "BlazorExtensions.Storage.Length"; |
| 49 | + public const string KEY_METHOD = "BlazorExtensions.Storage.Key"; |
| 50 | + public const string GET_ITEM_METHOD = "BlazorExtensions.Storage.GetItem"; |
| 51 | + public const string SET_ITEM_METHOD = "BlazorExtensions.Storage.SetItem"; |
| 52 | + public const string REMOVE_ITEM_METHOD = "BlazorExtensions.Storage.RemoveItem"; |
| 53 | + public const string CLEAR_METHOD = "BlazorExtensions.Storage.Clear"; |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments