This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
/
real-time-client.js
65 lines (56 loc) · 1.85 KB
/
real-time-client.js
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
const PeerPool = require('./peer-pool')
const Portal = require('./portal')
const {PortalCreationError, PortalNotFoundError} = require('./errors')
const PusherPubSubGateway = require('./pusher-pub-sub-gateway')
const RestGateway = require('./rest-gateway')
const NOOP = () => {}
module.exports =
class RealTimeClient {
constructor ({restGateway, pubSubGateway, testEpoch, pusherKey, baseURL, didCreateOrJoinPortal}) {
this.pusherKey = pusherKey
this.restGateway = restGateway || new RestGateway({baseURL})
this.pubSubGateway = pubSubGateway
this.testEpoch = testEpoch
this.didCreateOrJoinPortal = didCreateOrJoinPortal || NOOP
}
async initialize () {
if (!this.pubSubGateway) this.pubSubGateway = new PusherPubSubGateway({key: this.pusherKey})
this.peerId = await this.pubSubGateway.getClientId()
this.peerPool = new PeerPool({
peerId: this.peerId,
restGateway: this.restGateway,
pubSubGateway: this.pubSubGateway,
fragmentSize: 16 * 1024, // 16KB
testEpoch: this.testEpoch
})
await this.peerPool.initialize()
}
dispose () {
if (this.peerPool) this.peerPool.disconnect()
}
async createPortal () {
const {ok, body} = await this.restGateway.post('/portals', {
hostPeerId: this.peerId
})
if (ok) {
const {id} = body
const portal = new Portal({id, siteId: 1, peerPool: this.peerPool})
this.didCreateOrJoinPortal(portal)
return portal
} else {
throw new PortalCreationError()
}
}
async joinPortal (id) {
const {ok, body} = await this.restGateway.get(`/portals/${id}`)
if (ok) {
const {hostPeerId} = body
const portal = new Portal({id, hostPeerId, peerPool: this.peerPool})
await portal.join()
this.didCreateOrJoinPortal(portal)
return portal
} else {
throw new PortalNotFoundError()
}
}
}