Skip to content

Commit 951e0c9

Browse files
authored
fix: resolve transport sort order in browsers (libp2p#333)
* fix: resolve transport sort order in browsers * fix: update sort logic
1 parent bf4d926 commit 951e0c9

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

src/index.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,11 @@ class Switch extends EventEmitter {
127127

128128
// Only listen on transports we actually have addresses for
129129
return myTransports.filter((ts) => this.transports[ts].filter(myAddrs).length > 0)
130-
// push Circuit to be the last proto to be dialed
131-
.sort((a) => {
132-
return a === Circuit.tag ? 1 : 0
130+
// push Circuit to be the last proto to be dialed, and alphabetize the others
131+
.sort((a, b) => {
132+
if (a === Circuit.tag) return 1
133+
if (b === Circuit.tag) return -1
134+
return a < b ? -1 : 1
133135
})
134136
}
135137

test/switch.spec.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* eslint-env mocha */
2+
'use strict'
3+
4+
const chai = require('chai')
5+
const dirtyChai = require('dirty-chai')
6+
const expect = chai.expect
7+
chai.use(dirtyChai)
8+
9+
const Switch = require('../src')
10+
11+
describe('Switch', () => {
12+
describe('.availableTransports', () => {
13+
it('should always sort circuit last', () => {
14+
const switchA = new Switch({}, {})
15+
const transport = {
16+
filter: (addrs) => addrs
17+
}
18+
const mockPeerInfo = {
19+
multiaddrs: {
20+
toArray: () => ['a', 'b', 'c']
21+
}
22+
}
23+
24+
switchA.transports = {
25+
Circuit: transport,
26+
TCP: transport,
27+
WebSocketStar: transport
28+
}
29+
30+
expect(switchA.availableTransports(mockPeerInfo)).to.eql([
31+
'TCP',
32+
'WebSocketStar',
33+
'Circuit'
34+
])
35+
})
36+
})
37+
})

0 commit comments

Comments
 (0)