Refactoring: improve caching

This commit is contained in:
Pieter Vander Vennet 2023-04-18 23:44:49 +02:00
parent f203a1158d
commit e36e9123f3
5 changed files with 91 additions and 20 deletions

View file

@ -4,12 +4,14 @@ import { UIEventSource } from "../../UIEventSource"
/**
* A class which allows to read/write a tile to local storage.
*
* Does the heavy lifting for LocalStorageFeatureSource and SaveFeatureToLocalStorage
* Does the heavy lifting for LocalStorageFeatureSource and SaveFeatureToLocalStorage.
*
* Note: OSM-features with a negative id are ignored
*/
export default class TileLocalStorage<T> {
private static perLayer: Record<string, TileLocalStorage<any>> = {}
private readonly _layername: string
private readonly cachedSources: Record<number, UIEventSource<T>> = {}
private readonly cachedSources: Record<number, UIEventSource<T> & { flush: () => void }> = {}
private constructor(layername: string) {
this._layername = layername
@ -27,24 +29,26 @@ export default class TileLocalStorage<T> {
}
/**
* Constructs a UIEventSource element which is synced with localStorage
* @param layername
* @param tileIndex
* Constructs a UIEventSource element which is synced with localStorage.
* Supports 'flush'
*/
public getTileSource(tileIndex: number): UIEventSource<T> {
public getTileSource(tileIndex: number): UIEventSource<T> & { flush: () => void } {
const cached = this.cachedSources[tileIndex]
if (cached) {
return cached
}
const src = UIEventSource.FromPromise(this.GetIdb(tileIndex))
const src = <UIEventSource<T> & { flush: () => void }>(
UIEventSource.FromPromise(this.GetIdb(tileIndex))
)
src.flush = () => this.SetIdb(tileIndex, src.data)
src.addCallbackD((data) => this.SetIdb(tileIndex, data))
this.cachedSources[tileIndex] = src
return src
}
private SetIdb(tileIndex: number, data): void {
private async SetIdb(tileIndex: number, data): Promise<void> {
try {
IdbLocalStorage.SetDirectly(this._layername + "_" + tileIndex, data)
await IdbLocalStorage.SetDirectly(this._layername + "_" + tileIndex, data)
} catch (e) {
console.error(
"Could not save tile to indexed-db: ",
@ -52,7 +56,9 @@ export default class TileLocalStorage<T> {
"tileIndex is:",
tileIndex,
"for layer",
this._layername
this._layername,
"data is",
data
)
}
}