Improve the SVG fetching and caching logic (#2011)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -1,11 +1,10 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {SafeHtml} from '@angular/platform-browser';
|
||||
import {Observable, BehaviorSubject} from 'rxjs';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
|
||||
interface CachedIcon {
|
||||
content: string;
|
||||
sanitized: SafeHtml;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
@@ -13,25 +12,9 @@ interface CachedIcon {
|
||||
})
|
||||
export class IconCacheService {
|
||||
private cache = new Map<string, CachedIcon>();
|
||||
private readonly CACHE_DURATION_MS = 1000 * 60 * 60;
|
||||
|
||||
private cacheUpdate$ = new BehaviorSubject<string | null>(null);
|
||||
|
||||
getCachedContent(iconName: string): string | null {
|
||||
const cached = this.cache.get(iconName);
|
||||
|
||||
if (!cached) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
|
||||
this.cache.delete(iconName);
|
||||
return null;
|
||||
}
|
||||
|
||||
return cached.content;
|
||||
}
|
||||
|
||||
getCachedSanitized(iconName: string): SafeHtml | null {
|
||||
const cached = this.cache.get(iconName);
|
||||
|
||||
@@ -39,55 +22,22 @@ export class IconCacheService {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
|
||||
this.cache.delete(iconName);
|
||||
return null;
|
||||
}
|
||||
|
||||
return cached.sanitized;
|
||||
}
|
||||
|
||||
cacheIcon(iconName: string, content: string, sanitized: SafeHtml): void {
|
||||
this.cache.set(iconName, {
|
||||
content,
|
||||
sanitized,
|
||||
timestamp: Date.now()
|
||||
sanitized
|
||||
});
|
||||
this.cacheUpdate$.next(iconName);
|
||||
}
|
||||
|
||||
isCached(iconName: string): boolean {
|
||||
const cached = this.cache.get(iconName);
|
||||
|
||||
if (!cached) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Date.now() - cached.timestamp > this.CACHE_DURATION_MS) {
|
||||
this.cache.delete(iconName);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
removeIcon(iconName: string): boolean {
|
||||
return this.cache.delete(iconName);
|
||||
}
|
||||
|
||||
invalidate(iconName: string): void {
|
||||
this.cache.delete(iconName);
|
||||
this.cacheUpdate$.next(null);
|
||||
}
|
||||
|
||||
invalidateMultiple(iconNames: string[]): void {
|
||||
iconNames.forEach(name => this.cache.delete(name));
|
||||
this.cacheUpdate$.next(null);
|
||||
}
|
||||
|
||||
clearCache(): void {
|
||||
this.cache.clear();
|
||||
this.cacheUpdate$.next(null);
|
||||
}
|
||||
|
||||
getCacheUpdates(): Observable<string | null> {
|
||||
return this.cacheUpdate$.asObservable();
|
||||
getAllIconNames(): string[] {
|
||||
return Array.from(this.cache.keys()).sort();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user