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

subscription.ts

70 lines2.0 KB

1import type { LoadSubsetFn, UnloadSubsetFn } from '@tanstack/db'
2import type { ConvexClient } from 'convex/browser'
3import type { ConvexReactClient } from 'convex/react'
4import type {
5 FunctionArgs,
6 FunctionReference,
7 FunctionReturnType,
8} from 'convex/server'
9​
10export type ConvexCollectionClient =
11 Pick<ConvexClient, `onUpdate`> | Pick<ConvexReactClient, `watchQuery`>
12​
13export interface ConvexSubscription<T> {
14 loadSubset?: LoadSubsetFn
15 unloadSubset?: UnloadSubsetFn
16 getCurrentValue: () => T | undefined
17 unsubscribe: () => void
18 /** Wait for a complete authoritative snapshot, without waiting for DB visibility. */
19 waitForCurrent?: () => Promise<void>
21​
22export function subscribeQuery<TQuery extends FunctionReference<`query`>>(
23 client: ConvexCollectionClient,
24 query: TQuery,
25 args: FunctionArgs<TQuery>,
26 receive: (result: FunctionReturnType<TQuery>) => void,
27 fail: (error: unknown) => void,
28): ConvexSubscription<FunctionReturnType<TQuery>> {
29 let active = true
30 const stop = (unsubscribe: () => void) => () => {
31 active = false
32 unsubscribe()
33 }
34 if (`disabled` in client && client.disabled === true) {
35 throw new Error(`A disabled Convex client cannot sync a collection.`)
36 }
37 if (`onUpdate` in client) {
38 if (`closed` in client && client.closed === true) {
39 throw new Error(`A closed Convex client cannot sync a collection.`)
40 }
41 const subscription = client.onUpdate(
42 query,
43 args,
44 (value) => {
45 if (active) receive(value)
46 },
47 (error) => {
48 if (active) fail(error)
49 },
50 )
51 return {
52 getCurrentValue: () => subscription.getCurrentValue(),
53 unsubscribe: stop(subscription),
54 }
55 }
56 const watch = client.watchQuery(query, args)
57 const unsubscribe = watch.onUpdate(() => {
58 if (!active) return
59 try {
60 const result = watch.localQueryResult()
61 if (result !== undefined) receive(result)
62 } catch (error) {
63 fail(error)
64 }
65 })
66 return {
67 getCurrentValue: () => watch.localQueryResult(),
68 unsubscribe: stop(unsubscribe),
69 }