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

query-resource.ts

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