forked from gbezyuk/logux-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal-pair.js
113 lines (102 loc) · 2.65 KB
/
local-pair.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var NanoEvents = require('nanoevents')
function LocalConnection (pair, type) {
this.connected = false
this.emitter = new NanoEvents()
this.type = type
this.pair = pair
}
LocalConnection.prototype = {
other: function other () {
if (this.type === 'left') {
return this.pair.right
} else {
return this.pair.left
}
},
on: function on (event, listener) {
return this.emitter.on(event, listener)
},
connect: function connect () {
if (this.connected) {
throw new Error('Connection already established')
} else {
this.emitter.emit('connecting')
var self = this
return new Promise(function (resolve) {
setTimeout(function () {
self.other().connected = true
self.connected = true
self.other().emitter.emit('connect')
self.emitter.emit('connect')
resolve()
}, self.pair.delay)
})
}
},
disconnect: function disconnect (reason) {
if (!this.connected) {
throw new Error('Connection already finished')
} else {
this.connected = false
this.emitter.emit('disconnect', reason)
var self = this
return new Promise(function (resolve) {
setTimeout(function () {
self.other().connected = false
self.other().emitter.emit('disconnect')
resolve()
}, 1)
})
}
},
send: function send (message) {
if (this.connected) {
var self = this
setTimeout(function () {
self.other().emitter.emit('message', message)
}, self.pair.delay)
} else {
throw new Error('Connection should be started before sending a message')
}
}
}
/**
* Two paired loopback connections.
*
* @param {number} [delay=1] Delay for connection and send events.
*
* @example
* import { LocalPair } from 'logux-sync'
* const pair = new LocalPair()
* const client = new ClientSync(pair.left)
* const server = new ServerSync(pair.right)
*
* @class
*/
function LocalPair (delay) {
/**
* Delay for connection and send events to emulate real connection latency.
* @type {number}
*/
this.delay = delay || 1
/**
* First connection. Will be connected to {@link LocalPair#right} one
* after {@link Connection#connect}.
* @type {Connection}
*
* @example
* new ClientSync(pair.left)
*/
this.left = new LocalConnection(this, 'left')
/**
* Second connection. Will be connected to {@link LocalPair#left} one
* after {@link Connection#connect}.
* @type {Connection}
*
* @example
* new ServerSync(pair.right)
*/
this.right = new LocalConnection(this, 'right')
}
LocalPair.prototype = { }
module.exports = LocalPair