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

index.ts

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