forked from hplush/slowreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
59 lines (51 loc) · 1.44 KB
/
Copy pathclient.ts
File metadata and controls
59 lines (51 loc) · 1.44 KB
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
import type { ClientOptions } from '@logux/client'
import { Client } from '@logux/client'
import { TestPair, TestTime } from '@logux/core'
import { SUBPROTOCOL } from '@slowreader/api'
import { atom } from 'nanostores'
import { onEnvironment } from './environment.js'
import { SlowReaderError } from './error.js'
import { computeFrom, readonlyExport } from './lib/stores.js'
import { userId } from './settings.js'
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: Client | undefined
let $client = atom<Client | undefined>()
export const client = readonlyExport($client)
onEnvironment(({ logStoreCreator }) => {
let unbindUserId = computeFrom($client, [userId], user => {
prevClient?.destroy()
if (user) {
let logux = new Client({
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(): Client {
let logux = client.get()
if (!logux) {
throw new SlowReaderError('NoClient')
}
return logux
}