blog3000/Blog3000/Client/Services/CacheStorage.cs

93 lines
2.9 KiB
C#

using Microsoft.JSInterop;
using Blog3000.Client.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Blog3000.Client
{
public abstract class CacheStorage
{
private readonly string cacheId;
private readonly IJSRuntime jsRuntime;
private Task<bool> initedTask;
public CacheStorage(IJSRuntime jsRuntime)
{
this.jsRuntime = jsRuntime;
this.cacheId = GetCacheId();
initedTask = jsRuntime.InvokePromise<bool>($"MyCacheStorage.Create", new object[] { cacheId });
System.Diagnostics.Debug.WriteLine("CacheStorage init started");
}
public async Task Add(string url)
{
try
{
await initedTask;
await Task.Yield(); // Migitate 'Entry not found' problem?
await jsRuntime.InvokePromiseAsync<bool>($"{cacheId}.Add", url);
System.Diagnostics.Debug.WriteLine("Cache.Add done");
}
catch(Exception ex)
{
if (!ex.ToString().Contains("Entry was not found"))
{
throw ex;
}
else System.Diagnostics.Debug.WriteLine("Cache.Add: Ignoring Entry not found problem!");
}
}
public async Task AddAll(string[] urls)
{
// Work around bug in edge erroreneuosly reporting "Entry was not found" sometimge
// although successful, Therefore we must request each file single
foreach (var u in urls)
{
await Task.Yield();
await Add(u);
}
//await Task.Yield();
//await jsRuntime.InvokePromiseAsync<bool>($"{cacheId}.AddAll", urls);
//System.Diagnostics.Debug.WriteLine("Cache.AddAll done");
}
public async Task Delete(string url)
{
await initedTask;
await jsRuntime.InvokePromiseAsync<bool>($"{cacheId}.Delete", url);
System.Diagnostics.Debug.WriteLine("Cache.Delete done");
}
public async Task<bool> AreCached(string[] filters)
{
await initedTask;
var res = await jsRuntime.InvokePromiseAsync<bool>($"{cacheId}.AreCached", filters);
System.Diagnostics.Debug.WriteLine($"Cache.AreCached {res} done");
return res;
}
public async Task<string[]> MatchAll(string filter)
{
await initedTask;
var res = await jsRuntime.InvokePromiseAsync<string[]>($"{cacheId}.MatchAll", filter);
System.Diagnostics.Debug.WriteLine($"Cache.MatchAll {res?.Length ?? -1} done");
return res;
}
protected abstract string GetCacheId();
}
}