( query: QueryResourceSource<TValue>, )
| 42 | * @returns A Resource-compatible view of the query result. |
| 43 | */ |
| 44 | export function toResource<TValue>( |
| 45 | query: QueryResourceSource<TValue>, |
| 46 | ): QueryResource<TValue> { |
| 47 | // Intentionally does not use resource from snapshot to have |
| 48 | // support for the reload method for compatible libraries |
| 49 | const status = computed<ResourceStatus>(() => { |
| 50 | const fetchStatus = query.fetchStatus() |
| 51 | const data = query.data() |
| 52 | |
| 53 | if (fetchStatus === 'fetching' || fetchStatus === 'paused') { |
| 54 | return data === undefined ? 'loading' : 'reloading' |
| 55 | } |
| 56 | |
| 57 | switch (query.status()) { |
| 58 | case 'success': |
| 59 | return 'resolved' |
| 60 | case 'error': |
| 61 | return 'error' |
| 62 | case 'pending': |
| 63 | return 'idle' |
| 64 | } |
| 65 | }) |
| 66 | |
| 67 | const error = computed<Error | undefined>(() => { |
| 68 | return query.status() === 'error' |
| 69 | ? normalizeError(query.error()) |
| 70 | : undefined |
| 71 | }) |
| 72 | |
| 73 | const value = computed(() => { |
| 74 | if (status() === 'error') { |
| 75 | throw error() |
| 76 | } |
| 77 | |
| 78 | return query.data() |
| 79 | }) |
| 80 | |
| 81 | const snapshot = computed<ResourceSnapshot<TValue>>(() => { |
| 82 | const currentStatus = status() |
| 83 | |
| 84 | if (currentStatus === 'error') { |
| 85 | return { status: 'error', error: error()! } |
| 86 | } |
| 87 | |
| 88 | return { status: currentStatus, value: query.data() } |
| 89 | }) |
| 90 | |
| 91 | const hasValue = (() => |
| 92 | status() !== 'error' && |
| 93 | query.data() !== undefined) as QueryResource<TValue>['hasValue'] |
| 94 | |
| 95 | return { |
| 96 | value, |
| 97 | status, |
| 98 | error, |
| 99 | snapshot, |
| 100 | isLoading: computed(() => { |
| 101 | const currentStatus = status() |
no test coverage detected