mapcomplete/Logic/Web/IdbLocalStorage.ts

46 lines
1.4 KiB
TypeScript
Raw Normal View History

import {UIEventSource} from "../UIEventSource";
import * as idb from "idb-keyval"
import {Utils} from "../../Utils";
2022-01-18 18:52:42 +01:00
/**
* UIEventsource-wrapper around indexedDB key-value
*/
export class IdbLocalStorage {
2022-07-08 03:14:55 +02:00
private static readonly _sourceCache: Record<string, UIEventSource<any>> = {}
public static Get<T>(key: string, options?: { defaultValue?: T, whenLoaded?: (t: T | null) => void }): UIEventSource<T> {
2022-07-08 03:14:55 +02:00
if(IdbLocalStorage._sourceCache[key] !== undefined){
return IdbLocalStorage._sourceCache[key]
}
2022-01-26 21:40:38 +01:00
const src = new UIEventSource<T>(options?.defaultValue, "idb-local-storage:" + key)
if (Utils.runningFromConsole) {
return src;
}
src.addCallback(v => idb.set(key, v))
idb.get(key).then(v => {
src.setData(v ?? options?.defaultValue);
2022-01-26 21:40:38 +01:00
if (options?.whenLoaded !== undefined) {
options?.whenLoaded(v)
}
}).catch(err => {
console.warn("Loading from local storage failed due to", err)
if (options?.whenLoaded !== undefined) {
options?.whenLoaded(null)
}
})
2022-07-08 03:14:55 +02:00
IdbLocalStorage._sourceCache[key] = src;
return src;
2022-01-26 21:40:38 +01:00
}
2022-01-26 21:40:38 +01:00
public static SetDirectly(key: string, value) {
idb.set(key, value)
}
static GetDirectly(key: string) {
return idb.get(key)
}
}