@@ -33,13 +33,41 @@ class Messages extends EventEmitter {
33
33
34
34
this . _wss = wss
35
35
this . multiaddr = ''
36
+
37
+ wss . on ( 'connection' , ( ws , request ) => {
38
+ ws . on ( 'error' , error => debug ( `WebSocket Error: ${ error . stack } ` ) )
39
+
40
+ ws . once ( 'message' , ( buf ) => {
41
+ const path = request . url
42
+ const metadata = fromHeaders ( buf )
43
+ const channel = new WebSocketMessageChannel ( ws )
44
+
45
+ this . emit ( 'data' , {
46
+ path,
47
+ metadata,
48
+ channel
49
+ } )
50
+ } )
51
+ } )
52
+
53
+ wss . on ( 'error' , error => this . emit ( 'error' , error ) )
36
54
}
37
55
38
- async stop ( ) {
56
+ stop ( ) {
39
57
return new Promise ( ( resolve ) => {
40
58
this . _wss . close ( ( ) => resolve ( ) )
41
59
} )
42
60
}
61
+
62
+ ready ( ) {
63
+ return new Promise ( ( resolve ) => {
64
+ this . _wss . on ( 'listening' , ( ) => {
65
+ this . multiaddr = `/ip4/${ this . _wss . address ( ) . address } /tcp/${ this . _wss . address ( ) . port } /ws`
66
+
67
+ resolve ( this )
68
+ } )
69
+ } )
70
+ }
43
71
}
44
72
45
73
module . exports = async ( ipfs , options = { } ) => {
@@ -56,29 +84,5 @@ module.exports = async (ipfs, options = {}) => {
56
84
57
85
const messages = new Messages ( wss )
58
86
59
- wss . on ( 'connection' , function connection ( ws , request ) {
60
- ws . on ( 'error' , error => debug ( `WebSocket Error: ${ error . stack } ` ) )
61
-
62
- ws . once ( 'message' , function incoming ( buf ) {
63
- const path = request . url
64
- const metadata = fromHeaders ( buf )
65
- const channel = new WebSocketMessageChannel ( ws )
66
-
67
- messages . emit ( 'data' , {
68
- path,
69
- metadata,
70
- channel
71
- } )
72
- } )
73
- } )
74
-
75
- wss . on ( 'error' , error => messages . emit ( 'error' , error ) )
76
-
77
- return new Promise ( ( resolve ) => {
78
- wss . on ( 'listening' , ( ) => {
79
- messages . multiaddr = `/ip4/${ wss . address ( ) . address } /tcp/${ wss . address ( ) . port } /ws`
80
-
81
- resolve ( messages )
82
- } )
83
- } )
87
+ return messages . ready ( )
84
88
}
0 commit comments