Reuse connectionPromise for relay connect.

This commit is contained in:
Steve Perkins
2023-04-03 21:55:40 -04:00
committed by fiatjaf_
parent ce081bb4cb
commit f1eb9a3bc7
2 changed files with 13 additions and 13 deletions

18
pool.ts
View File

@@ -26,22 +26,16 @@ export class SimplePool {
async ensureRelay(url: string): Promise<Relay> {
const nm = normalizeURL(url)
const existing = this._conn[nm]
if (existing && existing.status === 1) return existing
if (existing) {
await existing.connect()
return existing
if (!this._conn[nm]) {
this._conn[nm] = relayInit(nm, {
getTimeout: this.getTimeout * 0.9,
listTimeout: this.getTimeout * 0.9
})
}
const relay = relayInit(nm, {
getTimeout: this.getTimeout * 0.9,
listTimeout: this.getTimeout * 0.9
})
this._conn[nm] = relay
const relay = this._conn[nm]
await relay.connect()
return relay
}

View File

@@ -83,8 +83,10 @@ export function relayInit(
}
} = {}
var connectionPromise: Promise<void> | undefined
async function connectRelay(): Promise<void> {
return new Promise((resolve, reject) => {
if (connectionPromise) return connectionPromise
connectionPromise = new Promise((resolve, reject) => {
try {
ws = new WebSocket(url)
} catch (err) {
@@ -96,10 +98,12 @@ export function relayInit(
resolve()
}
ws.onerror = () => {
connectionPromise = undefined
listeners.error.forEach(cb => cb())
reject()
}
ws.onclose = async () => {
connectionPromise = undefined
listeners.disconnect.forEach(cb => cb())
}
@@ -185,6 +189,8 @@ export function relayInit(
}
}
})
return connectionPromise
}
function connected() {