Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query-resource.ts

137 lines3.6 KB

1import { computed, untracked } from '@angular/core'
2import type { QueryObserverResult } from '@tanstack/query-core'
3import type { ResourceSnapshot } from './utils/resource-types'
4import type { Resource, ResourceStatus, Signal } from '@angular/core'
5​
6export interface QueryResource<TValue> extends Resource<TValue> {
7 /**
8 * The current query state as a single snapshot.
9 */
10 readonly snapshot: Signal<ResourceSnapshot<TValue>>
11​
12 /**
13 * Requests a new query fetch only when the current query data is stale.
14 *
15 * Used for compatibility with Angular APIs that might want to reload a resource,
16 * like Signal Forms' validateAsync resource interface.
17 *
18 * @returns `true` if a reload was initiated, `false` if a reload was unnecessary or unsupported.
19 */
20 reload: () => boolean
22​
23type QueryResourceSource<TValue> = {
24 readonly data: Signal<TValue>
25 readonly status: Signal<QueryObserverResult['status']>
26 readonly fetchStatus: Signal<QueryObserverResult['fetchStatus']>
27 readonly error: Signal<unknown>
28 readonly isStale: Signal<boolean>
29 readonly refetch: () => unknown
31​
32/**
33 * Converts an Angular Query result into Angular's Resource interface.
34 *
35 * Call this function once and reuse the returned resource.
36 *
37 * @param query An Angular Query or infinite-query result.
38 * @returns A Resource-compatible view of the query result.
39 */
40export function toResource<TValue>(
41 query: QueryResourceSource<TValue>,
42): QueryResource<TValue> {
43 // Intentionally does not use resource from snapshot to have
44 // support for the reload method for compatible libraries
45 const status = computed<ResourceStatus>(() => {
46 const fetchStatus = query.fetchStatus()
47 const data = query.data()
48​
49 if (fetchStatus === 'fetching' || fetchStatus === 'paused') {
50 return data === undefined ? 'loading' : 'reloading'
51 }
52​
53 switch (query.status()) {
54 case 'success':
55 return 'resolved'
56 case 'error':
57 return 'error'
58 case 'pending':
59 return 'idle'
60 }
61 })
62​
63 const error = computed<Error | undefined>(() => {
64 return query.status() === 'error'
65 ? normalizeError(query.error())
66 : undefined
67 })
68​
69 const value = computed(() => {
70 if (status() === 'error') {
71 throw error()
72 }
73​
74 return query.data()
75 })
76​
77 const snapshot = computed<ResourceSnapshot<TValue>>(() => {
78 const currentStatus = status()
79​
80 if (currentStatus === 'error') {
81 return { status: 'error', error: error()! }
82 }
83​
84 return { status: currentStatus, value: query.data() }
85 })
86​
87 const hasValue = (() =>
88 status() !== 'error' &&
89 query.data() !== undefined) as QueryResource<TValue>['hasValue']
90​
91 return {
92 value,
93 status,
94 error,
95 snapshot,
96 isLoading: computed(() => {
97 const currentStatus = status()
98 return currentStatus === 'loading' || currentStatus === 'reloading'
99 }),
100 hasValue,
101 reload(): boolean {
102 const currentStatus = untracked(status)
103 if (
104 currentStatus === 'idle' ||
105 currentStatus === 'loading' ||
106 currentStatus === 'reloading'
107 ) {
108 return false
109 }
110​
111 if (!untracked(query.isStale)) {
112 return false
113 }
114​
115 void query.refetch()
116 return true
117 },
118 }
120​
121function normalizeError(error: unknown): Error {
122 if (isErrorLike(error)) {
123 return error
124 }
125​
126 return new Error(String(error), { cause: error })
128​
129function isErrorLike(error: unknown): error is Error {
130 return (
131 error instanceof Error ||
132 (typeof error === 'object' &&
133 error !== null &&
134 typeof (error as Error).name === 'string' &&
135 typeof (error as Error).message === 'string')
136 )