2021-11-15 11:51:32 +01:00
|
|
|
import { UIEventSource } from "../UIEventSource"
|
|
|
|
import * as idb from "idb-keyval"
|
2022-01-06 14:39:42 +01:00
|
|
|
import { Utils } from "../../Utils"
|
2022-01-18 18:52:42 +01:00
|
|
|
|
2021-11-15 11:51:32 +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>> = {}
|
2022-09-08 21:40:48 +02:00
|
|
|
|
2022-03-24 03:11:29 +01:00
|
|
|
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) {
|
2022-01-06 14:39:42 +01:00
|
|
|
return src
|
|
|
|
}
|
2022-03-24 03:11:29 +01:00
|
|
|
src.addCallback((v) => idb.set(key, v))
|
2022-01-26 21:40:38 +01:00
|
|
|
|
2021-11-16 02:57:26 +01:00
|
|
|
idb.get(key)
|
2022-01-19 20:34:04 +01:00
|
|
|
.then((v) => {
|
|
|
|
src.setData(v ?? options?.defaultValue)
|
2022-03-24 03:11:29 +01:00
|
|
|
if (options?.whenLoaded !== undefined) {
|
2022-01-19 20:34:04 +01:00
|
|
|
options?.whenLoaded(v)
|
2022-09-08 21:40:48 +02:00
|
|
|
}
|
|
|
|
})
|
2022-03-24 03:11:29 +01:00
|
|
|
.catch((err) => {
|
|
|
|
console.warn("Loading from local storage failed due to", err)
|
|
|
|
if (options?.whenLoaded !== undefined) {
|
|
|
|
options?.whenLoaded(null)
|
2022-09-08 21:40:48 +02:00
|
|
|
}
|
|
|
|
})
|
2022-07-08 03:14:55 +02:00
|
|
|
IdbLocalStorage._sourceCache[key] = src
|
2021-11-15 11:51:32 +01:00
|
|
|
return src
|
|
|
|
}
|
2022-01-26 21:40:38 +01:00
|
|
|
|
2023-04-20 01:52:23 +02:00
|
|
|
public static SetDirectly(key: string, value: any): Promise<void> {
|
|
|
|
const copy = Utils.Clone(value)
|
|
|
|
return idb.set(key, copy)
|
2021-11-15 11:51:32 +01:00
|
|
|
}
|
|
|
|
|
2023-06-01 02:52:21 +02:00
|
|
|
static GetDirectly(key: string): Promise<any> {
|
2021-11-16 02:57:26 +01:00
|
|
|
return idb.get(key)
|
|
|
|
}
|
2021-11-15 11:51:32 +01:00
|
|
|
}
|