-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathuseSubscribe.ts
73 lines (62 loc) · 2 KB
/
useSubscribe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { useEffect } from 'react'
import { EJSON } from 'meteor/ejson'
import { Meteor } from 'meteor/meteor'
import isEqual from 'lodash.isequal'
import remove from 'lodash.remove'
const cachedSubscriptions: Entry[] = []
interface Entry {
params: EJSON[]
name: string
handle?: Meteor.SubscriptionHandle
promise: Promise<void>
result?: null
error?: unknown
}
const useSubscribeSuspenseClient = (name: string, ...params: EJSON[]) => {
const cachedSubscription =
cachedSubscriptions.find(x => x.name === name && isEqual(x.params, params))
useEffect(() =>
() => {
setTimeout(() => {
const cachedSubscription =
cachedSubscriptions.find(x => x.name === name && isEqual(x.params, params))
if (cachedSubscription) {
cachedSubscription.handle?.stop()
remove(cachedSubscriptions,
x =>
x.name === cachedSubscription.name &&
isEqual(x.params, cachedSubscription.params))
}
}, 0)
}, [name, EJSON.stringify(params)])
if (cachedSubscription != null) {
if ('error' in cachedSubscription) throw cachedSubscription.error
if ('result' in cachedSubscription) return cachedSubscription.result
throw cachedSubscription.promise
}
const subscription: Entry = {
name,
params,
promise: new Promise<Meteor.SubscriptionHandle>((resolve, reject) => {
const h = Meteor.subscribe(name, ...params, {
onReady() {
subscription.result = null
subscription.handle = h
resolve(h)
},
onStop(error: unknown) {
subscription.error = error
subscription.handle = h
reject(error)
}
})
})
}
cachedSubscriptions.push(subscription)
throw subscription.promise
}
const useSubscribeSuspenseServer = (name?: string, ...args: any[]) => undefined;
export const useSubscribeSuspense = Meteor.isServer
? useSubscribeSuspenseServer
: useSubscribeSuspenseClient
export const useSubscribe = useSubscribeSuspense