2023-05-02 00:58:55 +01:00
|
|
|
import type { MaybeRefOrGetter, RemovableRef } from '@vueuse/core'
|
2023-01-03 00:18:01 +00:00
|
|
|
import type { UseIDBOptions } from '@vueuse/integrations/useIDBKeyval'
|
2023-02-06 22:22:56 +00:00
|
|
|
import { del, get, set, update } from '~/utils/elk-idb'
|
2023-01-03 00:18:01 +00:00
|
|
|
|
2024-09-25 16:55:32 +01:00
|
|
|
export interface UseAsyncIDBKeyvalReturn<T> {
|
|
|
|
set: (value: T) => Promise<void>
|
|
|
|
readIDB: () => Promise<T | undefined>
|
|
|
|
}
|
2023-01-15 19:09:01 +00:00
|
|
|
|
2023-01-03 00:18:01 +00:00
|
|
|
export async function useAsyncIDBKeyval<T>(
|
|
|
|
key: IDBValidKey,
|
2023-05-02 00:58:55 +01:00
|
|
|
initialValue: MaybeRefOrGetter<T>,
|
2024-09-25 16:55:32 +01:00
|
|
|
source: RemovableRef<T>,
|
|
|
|
options: Omit<UseIDBOptions, 'shallow'> = {},
|
|
|
|
): Promise<UseAsyncIDBKeyvalReturn<T>> {
|
2023-01-03 00:18:01 +00:00
|
|
|
const {
|
|
|
|
flush = 'pre',
|
|
|
|
deep = true,
|
2024-09-25 16:55:32 +01:00
|
|
|
writeDefaults = true,
|
2023-01-03 00:18:01 +00:00
|
|
|
onError = (e: unknown) => {
|
|
|
|
console.error(e)
|
|
|
|
},
|
|
|
|
} = options
|
|
|
|
|
2024-08-20 16:51:05 +01:00
|
|
|
const rawInit: T = toValue<T>(initialValue)
|
2023-01-03 00:18:01 +00:00
|
|
|
|
2024-09-25 16:55:32 +01:00
|
|
|
try {
|
|
|
|
const rawValue = await get<T>(key)
|
|
|
|
if (rawValue === undefined) {
|
|
|
|
if (rawInit !== undefined && rawInit !== null && writeDefaults) {
|
|
|
|
await set(key, rawInit)
|
|
|
|
source.value = rawInit
|
2023-01-03 00:18:01 +00:00
|
|
|
}
|
|
|
|
}
|
2024-09-25 16:55:32 +01:00
|
|
|
else {
|
|
|
|
source.value = rawValue
|
2023-01-03 00:18:01 +00:00
|
|
|
}
|
|
|
|
}
|
2024-09-25 16:55:32 +01:00
|
|
|
catch (e) {
|
|
|
|
onError(e)
|
|
|
|
}
|
2023-01-03 00:18:01 +00:00
|
|
|
|
2024-09-25 16:55:32 +01:00
|
|
|
async function write(data: T) {
|
2023-01-03 00:18:01 +00:00
|
|
|
try {
|
2024-09-25 16:55:32 +01:00
|
|
|
if (data == null) {
|
2023-01-03 00:18:01 +00:00
|
|
|
await del(key)
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
// IndexedDB does not support saving proxies, convert from proxy before saving
|
2024-09-25 16:55:32 +01:00
|
|
|
await update(key, () => toRaw(data))
|
2023-01-03 00:18:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
onError(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-25 16:55:32 +01:00
|
|
|
const {
|
|
|
|
pause: pauseWatch,
|
|
|
|
resume: resumeWatch,
|
|
|
|
} = watchPausable(source, data => write(data), { flush, deep })
|
|
|
|
|
|
|
|
async function setData(value: T): Promise<void> {
|
|
|
|
pauseWatch()
|
|
|
|
try {
|
|
|
|
await write(value)
|
|
|
|
source.value = value
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
resumeWatch()
|
|
|
|
}
|
|
|
|
}
|
2023-01-03 00:18:01 +00:00
|
|
|
|
2024-09-25 16:55:32 +01:00
|
|
|
return { set: setData, readIDB: () => get<T>(key) }
|
2023-01-03 00:18:01 +00:00
|
|
|
}
|