forked from gbezyuk/logux-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local-pair.js
90 lines (79 loc) · 2.02 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
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.other().connected = true
this.connected = true
this.other().emitter.emit('connect')
this.emitter.emit('connect')
}
},
disconnect: function disconnect () {
if (this.connected) {
this.connected = false
this.other().connected = false
this.emitter.emit('disconnect')
this.other().emitter.emit('disconnect')
} else {
throw new Error('Connection already finished')
}
},
send: function send (message) {
if (this.connected) {
this.other().emitter.emit('message', message)
} else {
throw new Error('Connection should be started before sending a message')
}
}
}
/**
* Two paired loopback connections to be used in Logux tests
*
* @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 () {
/**
* 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