(params: {
get: () => T | Promise<T>;
set?: (value: T, valueRef: Ref<T>) => void;
initialValue?: T;
defaultValue?: T;
})
| 3 | import { computed, ref } from 'vue'; |
| 4 | |
| 5 | export function createSmartComputed<T>(params: { |
| 6 | get: () => T | Promise<T>; |
| 7 | set?: (value: T, valueRef: Ref<T>) => void; |
| 8 | initialValue?: T; |
| 9 | defaultValue?: T; |
| 10 | }) { |
| 11 | const valueRef = ref(params.initialValue) as Ref<T>; |
| 12 | |
| 13 | let counter = 0; |
| 14 | |
| 15 | let currentPromise: Promise<T> | undefined; |
| 16 | |
| 17 | const asyncComputed = computed(async () => { |
| 18 | const counterAtBeginning = ++counter; |
| 19 | |
| 20 | if ('defaultValue' in params) { |
| 21 | valueRef.value = params.defaultValue!; |
| 22 | } |
| 23 | |
| 24 | const result = params.get(); |
| 25 | |
| 26 | if (!isPromiseLike(result)) { |
| 27 | valueRef.value = result; |
| 28 | |
| 29 | return result; |
| 30 | } |
| 31 | |
| 32 | currentPromise = result; |
| 33 | |
| 34 | let promiseResult = await currentPromise; |
| 35 | |
| 36 | if (counterAtBeginning === counter) { |
| 37 | valueRef.value = promiseResult; |
| 38 | |
| 39 | currentPromise = undefined; |
| 40 | } |
| 41 | |
| 42 | while (currentPromise != null) { |
| 43 | promiseResult = await currentPromise; |
| 44 | } |
| 45 | |
| 46 | return promiseResult; |
| 47 | }); |
| 48 | |
| 49 | return { |
| 50 | getAsync: () => asyncComputed.value, |
| 51 | |
| 52 | get: (): T => { |
| 53 | void asyncComputed.value; |
| 54 | |
| 55 | return valueRef.value; |
| 56 | }, |
| 57 | set: (value: T) => { |
| 58 | if (params.set != null) { |
| 59 | return params.set?.(value, valueRef); |
| 60 | } else { |
| 61 | return (valueRef.value = value); |
| 62 | } |
no test coverage detected