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