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

createCacheSubscriptionRegistry.ts

62 lines1.8 KB

1import { onCleanup } from 'solid-js'
2import type { Accessor, Setter } from 'solid-js'
3​
4/**
5 * Creates a registry of components subscribed to a cache, so each one only
6 * updates for the cache events it cares about.
7 *
8 * @returns The `register` and `notify` functions of the registry.
9 */
10export function createCacheSubscriptionRegistry<TCache, TEvent>() {
11 const subscriptions = new Map<
12 symbol,
13 {
14 shouldUpdate: (event: TEvent) => boolean
15 update: (cache: Accessor<TCache>) => void
16 }
17 >()
18​
19 /**
20 * Registers a subscription that is removed when the current owner is cleaned
21 * up.
22 *
23 * @param callback - Computes the value from the cache.
24 * @param setter - Receives the computed value on every update.
25 * @param shouldUpdate - Decides whether an event updates this subscription.
26 * Defaults to every event.
27 */
28 function register<T>(
29 callback: (cache: Accessor<TCache>) => Exclude<T, Function>,
30 setter: Setter<T>,
31 shouldUpdate: (event: TEvent) => boolean = () => true,
32 ) {
33 const id = Symbol()
34 subscriptions.set(id, {
35 shouldUpdate,
36 update: (cache) => setter(callback(cache)),
37 })
38 onCleanup(() => subscriptions.delete(id))
39 }
40​
41 /**
42 * Updates every subscription whose `shouldUpdate` accepts the event.
43 *
44 * @param cache - The cache to compute the values from.
45 * @param event - The cache event.
46 * @param schedule - Runs each update. Defaults to running it right away.
47 */
48 function notify(
49 cache: Accessor<TCache>,
50 event: TEvent,
51 schedule: (update: () => void) => void = (update) => update(),
52 ) {
53 for (const [id, subscription] of subscriptions) {
54 if (!subscription.shouldUpdate(event)) continue
55 schedule(() => {
56 if (subscriptions.has(id)) subscription.update(cache)
57 })
58 }
59 }
60​
61 return { register, notify }