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

index.ts

215 lines6.0 KB

1import { BroadcastChannel } from 'broadcast-channel'
2import type { QueryClient, QueryKey } from '@tanstack/query-core'
3import type { BroadcastChannelOptions } from 'broadcast-channel'
4​
5/**
6 * Metadata describing a broadcast that failed to be delivered to other tabs.
7 * Passed to {@link BroadcastQueryClientOptions.onBroadcastError} so callers
8 * can correlate failures with the originating query.
9 */
10export interface BroadcastErrorEvent {
11 /**
12 * The kind of cache event that was being broadcast.
13 */
14 type: 'updated' | 'removed' | 'added'
15 /**
16 * The hash of the query the broadcast was about.
17 */
18 queryHash: string
19 /**
20 * The key of the query the broadcast was about.
21 */
22 queryKey: QueryKey
24​
25type BroadcastMessage =
26 | { type: 'updated'; queryHash: string; queryKey: QueryKey; state: unknown }
27 | { type: 'removed'; queryHash: string; queryKey: QueryKey }
28 | { type: 'added'; queryHash: string; queryKey: QueryKey; state: unknown }
29​
30interface BroadcastQueryClientOptions {
31 /** The QueryClient to sync. */
32 queryClient: QueryClient
33 /**
34 * Unique channel name used to communicate between tabs and windows.
35 * @default 'tanstack-query'
36 */
37 broadcastChannel?: string
38 /** Options forwarded to the underlying `BroadcastChannel`. */
39 options?: BroadcastChannelOptions
40 /**
41 * Called when a query event fails to broadcast to other tabs β€” most
42 * commonly because the query's `state.data`, `state.error`, or `queryKey`
43 * contains a value the structured-clone algorithm cannot serialize
44 * (e.g. `ReadableStream`, `File`, functions, Vue `reactive` proxies).
45 *
46 * Provide this to route failures to an error tracker. If omitted, a
47 * `console.warn` is emitted in development so failures are never silent.
48 *
49 * May return a `Promise`; any rejection is caught internally so it cannot
50 * cause a secondary unhandled rejection.
51 */
52 onBroadcastError?: (
53 error: unknown,
54 event: BroadcastErrorEvent,
55 ) => void | Promise<void>
57​
58/**
59 * Syncs a client's query cache with the caches of other tabs and windows through a
60 * `BroadcastChannel`: added queries, successful updates, and removals of queries that have
61 * observers are broadcast, and those received from other tabs are applied.
62 * @param options - The `queryClient` to sync, the `broadcastChannel` name, the channel `options`,
63 * and the `onBroadcastError` callback.
64 * @returns A function that stops syncing and closes the channel.
65 */
66export function broadcastQueryClient({
67 queryClient,
68 broadcastChannel = 'tanstack-query',
69 options,
70 onBroadcastError,
71}: BroadcastQueryClientOptions): () => void {
72 let transaction = false
73 const tx = (cb: () => void) => {
74 transaction = true
75 try {
76 cb()
77 } finally {
78 // Guard against `cb` throwing (e.g. `query.setState`/`queryCache.build`
79 // triggering a listener that throws while applying an incoming
80 // cross-tab message). Without this, `transaction` would stay `true`
81 // forever, silently disabling this tab's own broadcasts to other tabs
82 // for the rest of the session.
83 transaction = false
84 }
85 }
86​
87 const channel = new BroadcastChannel(broadcastChannel, {
88 webWorkerSupport: false,
89 ...options,
90 })
91​
92 const queryCache = queryClient.getQueryCache()
93​
94 const safePost = (message: BroadcastMessage): void => {
95 channel.postMessage(message).catch((error: unknown) => {
96 const event: BroadcastErrorEvent = {
97 type: message.type,
98 queryHash: message.queryHash,
99 queryKey: message.queryKey,
100 }
101​
102 if (onBroadcastError) {
103 const warnCallbackError = (callbackError: unknown) => {
104 if (process.env.NODE_ENV !== 'production') {
105 console.warn(
106 `[broadcastQueryClient] onBroadcastError threw while handling "${event.type}" for query ${event.queryHash}.`,
107 callbackError,
108 )
109 }
110 }
111 let result: void | Promise<void>
112 try {
113 result = onBroadcastError(error, event)
114 } catch (callbackError) {
115 warnCallbackError(callbackError)
116 return
117 }
118 result?.catch(warnCallbackError)
119 } else if (process.env.NODE_ENV !== 'production') {
120 console.warn(
121 `[broadcastQueryClient] Failed to broadcast "${event.type}" event for query ${event.queryHash}. ` +
122 'The query value could not be structured-cloned; cross-tab sync for this query was skipped.',
123 error,
124 )
125 }
126 })
127 }
128​
129 const unsubscribe = queryCache.subscribe((queryEvent) => {
130 if (transaction) {
131 return
132 }
133​
134 const {
135 query: { queryHash, queryKey, state, observers },
136 } = queryEvent
137​
138 if (queryEvent.type === 'updated' && queryEvent.action.type === 'success') {
139 safePost({
140 type: 'updated',
141 queryHash,
142 queryKey,
143 state,
144 })
145 }
146​
147 if (queryEvent.type === 'removed' && observers.length > 0) {
148 safePost({
149 type: 'removed',
150 queryHash,
151 queryKey,
152 })
153 }
154​
155 if (queryEvent.type === 'added') {
156 safePost({
157 type: 'added',
158 queryHash,
159 queryKey,
160 state,
161 })
162 }
163 })
164​
165 channel.onmessage = (action) => {
166 if (!action?.type) {
167 return
168 }
169​
170 tx(() => {
171 const { type, queryHash, queryKey, state } = action
172​
173 const query = queryCache.get(queryHash)
174​
175 if (type === 'updated') {
176 if (query) {
177 query.setState(state)
178 return
179 }
180​
181 queryCache.build(
182 queryClient,
183 {
184 queryKey,
185 queryHash,
186 },
187 state,
188 )
189 } else if (type === 'removed') {
190 if (query) {
191 queryCache.remove(query)
192 }
193 } else if (type === 'added') {
194 if (query) {
195 if (query.state.data === undefined) {
196 query.setState(state)
197 }
198 return
199 }
200 queryCache.build(
201 queryClient,
202 {
203 queryKey,
204 queryHash,
205 },
206 state,
207 )
208 }
209 })
210 }
211 return () => {
212 unsubscribe()
213 channel.close()
214 }