/
group.test.ts
82 lines (74 loc) · 2.14 KB
/
group.test.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
74
75
76
77
78
79
80
81
82
import { MessageChannel } from 'node:worker_threads'
import { expect, it } from 'vitest'
import { createBirpc, createBirpcGroup } from '../src'
import * as Bob from './bob'
import * as Alice from './alice'
type BobFunctions = typeof Bob
type AliceFunctions = typeof Alice
it('group', async () => {
const channel1 = new MessageChannel()
const channel2 = new MessageChannel()
const channel3 = new MessageChannel()
const client1 = createBirpc<AliceFunctions, BobFunctions>(
Bob,
{
post: data => channel1.port1.postMessage(data),
on: async (data) => {
await new Promise(resolve => setTimeout(resolve, 100))
channel1.port1.on('message', data)
},
},
)
const client2 = createBirpc<AliceFunctions, BobFunctions>(
Bob,
{
post: data => channel2.port1.postMessage(data),
on: data => channel2.port1.on('message', data),
},
)
const client3 = createBirpc<AliceFunctions, BobFunctions>(
Bob,
{
post: data => channel3.port1.postMessage(data),
on: data => channel3.port1.on('message', data),
},
)
const server = createBirpcGroup<BobFunctions, AliceFunctions>(
Alice,
[
{
post: data => channel1.port2.postMessage(data),
on: data => channel1.port2.on('message', data),
},
{
post: data => channel2.port2.postMessage(data),
on: data => channel2.port2.on('message', data),
},
],
{ eventNames: ['bump'] },
)
// RPCs
expect(await client1.hello('Bob'))
.toEqual('Hello Bob, my name is Alice')
expect(await client2.hello('Bob'))
.toEqual('Hello Bob, my name is Alice')
expect(await server.broadcast.hi('Alice'))
.toEqual([
'Hi Alice, I am Bob',
'Hi Alice, I am Bob',
])
server.updateChannels((channels) => {
channels.push({
post: data => channel3.port2.postMessage(data),
on: data => channel3.port2.on('message', data),
})
})
expect(await server.broadcast.hi('Alice'))
.toEqual([
'Hi Alice, I am Bob',
'Hi Alice, I am Bob',
'Hi Alice, I am Bob',
])
expect(await client3.hello('Bob'))
.toEqual('Hello Bob, my name is Alice')
})