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

createCacheSubscriptionRegistry.ts

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