-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathclient.ts
57 lines (49 loc) · 1.41 KB
/
client.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
import { type ClientOptions, CrossTabClient } from '@logux/client'
import { TestPair, TestTime } from '@logux/core'
import { SUBPROTOCOL } from '@slowreader/api'
import { atom } from 'nanostores'
import { onEnvironment } from './environment.ts'
import { computeFrom, readonlyExport } from './lib/stores.ts'
import { userId } from './settings.ts'
let testTime: TestTime | undefined
export function enableTestTime(): TestTime {
testTime = new TestTime()
return testTime
}
function getServer(): ClientOptions['server'] {
return testTime ? new TestPair().left : 'ws://localhost:31337/'
}
let prevClient: CrossTabClient | undefined
let $client = atom<CrossTabClient | undefined>()
export const client = readonlyExport($client)
onEnvironment(({ logStoreCreator }) => {
let unbindUserId = computeFrom($client, [userId], user => {
prevClient?.destroy()
if (user) {
let logux = new CrossTabClient({
prefix: 'slowreader',
server: getServer(),
store: logStoreCreator(),
subprotocol: SUBPROTOCOL,
time: testTime,
userId: user
})
logux.start(false)
prevClient = logux
return logux
} else {
return undefined
}
})
return () => {
unbindUserId()
prevClient?.destroy()
}
})
export function getClient(): CrossTabClient {
let logux = client.get()
if (!logux) {
throw new Error('No Slow Reader client')
}
return logux
}