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

index.ts

327 lines10.5 KB

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