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

index.ts

326 lines10.3 KB

1import {
2 DestroyRef,
3 assertInInjectionContext,
4 computed,
5 effect,
6 inject,
7 signal,
8} from '@angular/core'
9import {
10 BaseQueryBuilder,
11 createLiveQueryCollection,
12 createLiveQueryObserver,
13 isCollection,
14 isSingleResultCollection,
15} from '@tanstack/db'
16import type {
17 Collection,
18 CollectionStatus,
19 Context,
20 GetResult,
21 InferResultType,
22 InitialQueryBuilder,
23 LiveQueryCollectionConfig,
24 LiveQueryObserver,
25 LiveQueryPersistedStatus,
26 NonSingleResult,
27 QueryBuilder,
28 SingleResult,
29} from '@tanstack/db'
30import type { Signal } from '@angular/core'
31​
32export * from '@tanstack/db'
33​
34/**
35 * The result of calling `injectLiveQuery`.
36 * Contains reactive signals for the query state and data.
37 */
38export interface InjectLiveQueryResult<TContext extends Context> {
39 /** A signal containing the complete state map of results keyed by their ID */
40 state: Signal<Map<string | number, GetResult<TContext>>>
41 /** A signal containing the results as an array, or single result for findOne queries */
42 data: Signal<InferResultType<TContext>>
43 /** A signal containing the underlying collection instance (null for disabled queries) */
44 collection: Signal<Collection<
45 GetResult<TContext>,
46 string | number,
47 {}
48 > | null>
49 /** A signal containing the current status of the collection */
50 status: Signal<CollectionStatus | `disabled`>
51 /** A signal indicating whether the collection is currently loading */
52 isLoading: Signal<boolean>
53 /** A signal indicating whether the collection is ready */
54 isReady: Signal<boolean>
55 persistedStatus: Signal<LiveQueryPersistedStatus>
56 isPersistedReady: Signal<boolean>
57 persistedError: Signal<unknown | undefined>
58 /** A signal indicating whether the collection is idle */
59 isIdle: Signal<boolean>
60 /** A signal indicating whether the collection has an error */
61 isError: Signal<boolean>
62 /** A signal indicating whether the collection has been cleaned up */
63 isCleanedUp: Signal<boolean>
65​
66type InferConditionalResultType<TContext extends Context> =
67 TContext extends SingleResult
68 ? InferResultType<TContext> | []
69 : InferResultType<TContext>
70​
71export type InjectConditionalLiveQueryResult<TContext extends Context> = Omit<
72 InjectLiveQueryResult<TContext>,
73 `data`
74> & {
75 data: Signal<InferConditionalResultType<TContext>>
77​
78export interface InjectLiveQueryResultWithCollection<
79 TResult extends object = any,
80 TKey extends string | number = string | number,
81 TUtils extends Record<string, any> = {},
82> {
83 state: Signal<Map<TKey, TResult>>
84 data: Signal<Array<TResult>>
85 collection: Signal<Collection<TResult, TKey, TUtils> | null>
86 status: Signal<CollectionStatus | `disabled`>
87 isLoading: Signal<boolean>
88 isReady: Signal<boolean>
89 persistedStatus: Signal<LiveQueryPersistedStatus>
90 isPersistedReady: Signal<boolean>
91 persistedError: Signal<unknown | undefined>
92 isIdle: Signal<boolean>
93 isError: Signal<boolean>
94 isCleanedUp: Signal<boolean>
96​
97export interface InjectLiveQueryResultWithSingleResultCollection<
98 TResult extends object = any,
99 TKey extends string | number = string | number,
100 TUtils extends Record<string, any> = {},
101> {
102 state: Signal<Map<TKey, TResult>>
103 data: Signal<TResult | undefined>
104 collection: Signal<(Collection<TResult, TKey, TUtils> & SingleResult) | null>
105 status: Signal<CollectionStatus | `disabled`>
106 isLoading: Signal<boolean>
107 isReady: Signal<boolean>
108 persistedStatus: Signal<LiveQueryPersistedStatus>
109 isPersistedReady: Signal<boolean>
110 persistedError: Signal<unknown | undefined>
111 isIdle: Signal<boolean>
112 isError: Signal<boolean>
113 isCleanedUp: Signal<boolean>
115​
116export function injectLiveQuery<
117 TContext extends Context,
118 TParams extends any,
119>(options: {
120 params: () => TParams
121 query: (args: {
122 params: TParams
123 q: InitialQueryBuilder
124 }) => QueryBuilder<TContext>
125}): InjectLiveQueryResult<TContext>
126export function injectLiveQuery<
127 TContext extends Context,
128 TParams extends any,
129>(options: {
130 params: () => TParams
131 query: (args: {
132 params: TParams
133 q: InitialQueryBuilder
134 }) => QueryBuilder<TContext> | undefined | null
135}): InjectConditionalLiveQueryResult<TContext>
136export function injectLiveQuery<TContext extends Context>(
137 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
138): InjectLiveQueryResult<TContext>
139export function injectLiveQuery<TContext extends Context>(
140 queryFn: (
141 q: InitialQueryBuilder,
142 ) => QueryBuilder<TContext> | undefined | null,
143): InjectConditionalLiveQueryResult<TContext>
144export function injectLiveQuery<TContext extends Context>(
145 config: LiveQueryCollectionConfig<TContext>,
146): InjectLiveQueryResult<TContext>
147// Pre-created collection without singleResult
148export function injectLiveQuery<
149 TResult extends object,
150 TKey extends string | number,
151 TUtils extends Record<string, any>,
152>(
153 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
154): InjectLiveQueryResultWithCollection<TResult, TKey, TUtils>
155// Pre-created collection with singleResult
156export function injectLiveQuery<
157 TResult extends object,
158 TKey extends string | number,
159 TUtils extends Record<string, any>,
160>(
161 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
162): InjectLiveQueryResultWithSingleResultCollection<TResult, TKey, TUtils>
163export function injectLiveQuery(opts: any) {
164 assertInInjectionContext(injectLiveQuery)
165 const destroyRef = inject(DestroyRef)
166​
167 const collection = computed(() => {
168 // Check if it's an existing collection
169 if (isCollection(opts)) {
170 return opts
171 }
172​
173 if (typeof opts === `function`) {
174 // Check if query function returns null/undefined (disabled query)
175 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
176 const result = opts(queryBuilder)
177​
178 if (result === undefined || result === null) {
179 // Disabled query - return null
180 return null
181 }
182​
183 return createLiveQueryCollection({
184 query: opts,
185 startSync: true,
186 gcTime: 0,
187 })
188 }
189​
190 // Check if it's reactive query options
191 const isReactiveQueryOptions =
192 opts &&
193 typeof opts === `object` &&
194 typeof opts.query === `function` &&
195 typeof opts.params === `function`
196​
197 if (isReactiveQueryOptions) {
198 const { params, query } = opts
199 const currentParams = params()
200​
201 // Check if query function returns null/undefined (disabled query)
202 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
203 const result = query({ params: currentParams, q: queryBuilder })
204​
205 if (result === undefined || result === null) {
206 // Disabled query - return null
207 return null
208 }
209​
210 return createLiveQueryCollection({
211 query: () => result,
212 startSync: true,
213 gcTime: 0,
214 })
215 }
216​
217 // Handle LiveQueryCollectionConfig objects. Default startSync/gcTime to
218 // match the query-fn and reactive-options paths, but let an explicit value
219 // in the config win — otherwise a bare `{ query }` never syncs.
220 if (opts && typeof opts === `object` && typeof opts.query === `function`) {
221 return createLiveQueryCollection({ startSync: true, gcTime: 0, ...opts })
222 }
223​
224 throw new Error(`Invalid options provided to injectLiveQuery`)
225 })
226​
227 const state = signal(new Map<string | number, any>())
228 const internalData = signal<Array<any>>([])
229 const statusValue = signal<CollectionStatus | `disabled`>(`idle`)
230 const status = computed(() => {
231 const value = statusValue()
232 return value === `idle` && !collection() ? `disabled` : value
233 })
234 const persistedStatus = signal<LiveQueryPersistedStatus>(`unavailable`)
235 const persistedError = signal<unknown>(undefined)
236​
237 // Returns single item for singleResult collections, array otherwise
238 const data = computed(() => {
239 const currentCollection = collection()
240 if (!currentCollection) {
241 return internalData()
242 }
243 return isSingleResultCollection(currentCollection)
244 ? internalData()[0]
245 : internalData()
246 })
247​
248 const syncDataFromCollection = (
249 currentCollection: Collection<any, any, any>,
250 observer: LiveQueryObserver<any, any>,
251 ) => {
252 const newState = new Map(currentCollection.entries())
253 const newData = Array.from(currentCollection.values())
254​
255 state.set(newState)
256 internalData.set(newData)
257 const snapshot = observer.getSnapshot()
258 statusValue.set(snapshot.status)
259 persistedStatus.set(snapshot.persistedStatus)
260 persistedError.set(snapshot.persistedError)
261 }
262​
263 let unsub: (() => void) | null = null
264 const cleanup = () => {
265 unsub?.()
266 unsub = null
267 }
268​
269 effect((onCleanup) => {
270 const currentCollection = collection()
271​
272 // Handle null collection (disabled query)
273 if (!currentCollection) {
274 statusValue.set(`disabled` as const)
275 persistedStatus.set(`unavailable`)
276 persistedError.set(undefined)
277 state.set(new Map())
278 internalData.set([])
279 cleanup()
280 return
281 }
282​
283 cleanup()
284​
285 // The shared observer owns sync start, subscription, the ready-race, and
286 // status transitions; Angular re-reads the whole collection on each notify
287 // (wholesale) into its signals.
288 // Angular re-reads the collection on notify; wholesale mode preserves its
289 // pre-observer loading policy (no initial-state snapshot request).
290 const observer = createLiveQueryObserver(currentCollection, {
291 mode: `wholesale`,
292 })
293​
294 const unsubscribe = observer.subscribe(() => {
295 syncDataFromCollection(currentCollection, observer)
296 })
297 // Wholesale attach suppresses listener calls raised by synchronous sync
298 // startup. Read once after subscribe returns to capture that final state.
299 syncDataFromCollection(currentCollection, observer)
300 unsub = () => {
301 unsubscribe()
302 observer.dispose()
303 }
304​
305 onCleanup(cleanup)
306 })
307​
308 destroyRef.onDestroy(cleanup)
309​
310 return {
311 state,
312 data,
313 // Loosely typed so the impl return stays compatible with every overload
314 // (the shared `isCollection` guard narrows the computed to `Collection | null`).
315 collection: collection as Signal<any>,
316 status,
317 isLoading: computed(() => status() === `loading`),
318 isReady: computed(() => status() === `ready` || status() === `disabled`),
319 persistedStatus,
320 isPersistedReady: computed(() => persistedStatus() === `ready`),
321 persistedError,
322 isIdle: computed(() => status() === `idle`),
323 isError: computed(() => status() === `error`),
324 isCleanedUp: computed(() => status() === `cleaned-up`),
325 }