Open History to see the last commit
1import { computed, untracked } from '@angular/core'
2import type { Resource, ResourceStatus, Signal } from '@angular/core'
3import type { QueryObserverResult } from '@tanstack/query-core'
4import type { ResourceSnapshot } from './utils/resource-types'
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
23}
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
32}
33β
34/**
35 * Converts an Angular Query result into Angular's Resource interface.
36 *
37 * Warning: experimental feature. The API may change in minor and patch releases.
38 * Pin your package version to an exact version when using this feature.
39 *
40 * Call this function once and reuse the returned resource.
41 * @param query - An Angular Query or infinite-query result.
42 * @returns A Resource-compatible view of the query result.
43 */
44export 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()
102 return currentStatus === 'loading' || currentStatus === 'reloading'
103 }),
104 hasValue,
105 reload(): boolean {
106 const currentStatus = untracked(status)
107 if (
108 currentStatus === 'idle' ||
109 currentStatus === 'loading' ||
110 currentStatus === 'reloading'
111 ) {
112 return false
113 }
114β
115 if (!untracked(query.isStale)) {
116 return false
117 }
118β
119 void query.refetch()
120 return true
121 },
122 }
123}
124β
125/**
126 * Converts an unknown rejection reason to an Error-compatible value.
127 * @param error - The rejected value.
128 * @returns The existing error-like value, or an Error wrapping the rejection.
129 */
130function normalizeError(error: unknown): Error {
131 if (isErrorLike(error)) {
132 return error
133 }
134β
135 return new Error(String(error), { cause: error })
136}
137β
138/**
139 * Checks whether a value provides the name and message of an Error.
140 * @param error - The value to inspect.
141 * @returns Whether the value can be used as an Error.
142 */
143function isErrorLike(error: unknown): error is Error {
144 return (
145 error instanceof Error ||
146 (typeof error === 'object' &&
147 error !== null &&
148 typeof (error as Error).name === 'string' &&
149 typeof (error as Error).message === 'string')
150 )
151}