Skip to content

Commit ae75570

Browse files
authored
fix: return empty address list during listen operation (#2904)
If `getAddrs` is called on a WS listener after `.listen` has been called but before any socket(s) have opened, return an empty list instead of throwing. Fixes #2902
1 parent 7caee9f commit ae75570

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

packages/transport-websockets/src/listener.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -341,20 +341,20 @@ export class WebSocketListener extends TypedEventEmitter<ListenerEvents> impleme
341341
}
342342

343343
getAddrs (): Multiaddr[] {
344+
if (this.listeningMultiaddr == null) {
345+
throw new Error('Listener is not ready yet')
346+
}
347+
344348
const address = this.server.address()
345349

346350
if (address == null) {
347-
throw new Error('Listener is not ready yet')
351+
return []
348352
}
349353

350354
if (typeof address === 'string') {
351355
throw new Error('Wrong address type received - expected AddressInfo, got string - are you trying to listen on a unix socket?')
352356
}
353357

354-
if (this.listeningMultiaddr == null) {
355-
throw new Error('Listener is not ready yet')
356-
}
357-
358358
const options = this.listeningMultiaddr.toOptions()
359359
const multiaddrs: Multiaddr[] = []
360360

packages/transport-websockets/test/node.ts

+16
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,22 @@ describe('listen', () => {
7373
void listener.listen(ma)
7474
})
7575

76+
it('should return an empty address list when `getAddrs` called before listening has finished', async () => {
77+
listener = ws.createListener({ upgrader })
78+
79+
void listener.listen(ma)
80+
81+
// call getAddrs before sockets have opened
82+
expect(listener.getAddrs()).to.be.empty()
83+
})
84+
85+
it('should throw when `.getAddrs` called before `.listen`', async () => {
86+
listener = ws.createListener({ upgrader })
87+
88+
// call getAddrs before sockets have opened
89+
expect(() => listener.getAddrs()).to.throw(/not ready/)
90+
})
91+
7692
it('should error on starting two listeners on same address', async () => {
7793
listener = ws.createListener({ upgrader })
7894
const dumbServer = http.createServer()

0 commit comments

Comments
 (0)