mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-17 04:18:50 +00:00
Reuse connectionPromise for relay connect.
This commit is contained in:
18
pool.ts
18
pool.ts
@@ -26,22 +26,16 @@ export class SimplePool {
|
|||||||
|
|
||||||
async ensureRelay(url: string): Promise<Relay> {
|
async ensureRelay(url: string): Promise<Relay> {
|
||||||
const nm = normalizeURL(url)
|
const nm = normalizeURL(url)
|
||||||
const existing = this._conn[nm]
|
|
||||||
if (existing && existing.status === 1) return existing
|
|
||||||
|
|
||||||
if (existing) {
|
if (!this._conn[nm]) {
|
||||||
await existing.connect()
|
this._conn[nm] = relayInit(nm, {
|
||||||
return existing
|
getTimeout: this.getTimeout * 0.9,
|
||||||
|
listTimeout: this.getTimeout * 0.9
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const relay = relayInit(nm, {
|
const relay = this._conn[nm]
|
||||||
getTimeout: this.getTimeout * 0.9,
|
|
||||||
listTimeout: this.getTimeout * 0.9
|
|
||||||
})
|
|
||||||
this._conn[nm] = relay
|
|
||||||
|
|
||||||
await relay.connect()
|
await relay.connect()
|
||||||
|
|
||||||
return relay
|
return relay
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
8
relay.ts
8
relay.ts
@@ -83,8 +83,10 @@ export function relayInit(
|
|||||||
}
|
}
|
||||||
} = {}
|
} = {}
|
||||||
|
|
||||||
|
var connectionPromise: Promise<void> | undefined
|
||||||
async function connectRelay(): Promise<void> {
|
async function connectRelay(): Promise<void> {
|
||||||
return new Promise((resolve, reject) => {
|
if (connectionPromise) return connectionPromise
|
||||||
|
connectionPromise = new Promise((resolve, reject) => {
|
||||||
try {
|
try {
|
||||||
ws = new WebSocket(url)
|
ws = new WebSocket(url)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -96,10 +98,12 @@ export function relayInit(
|
|||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
ws.onerror = () => {
|
ws.onerror = () => {
|
||||||
|
connectionPromise = undefined
|
||||||
listeners.error.forEach(cb => cb())
|
listeners.error.forEach(cb => cb())
|
||||||
reject()
|
reject()
|
||||||
}
|
}
|
||||||
ws.onclose = async () => {
|
ws.onclose = async () => {
|
||||||
|
connectionPromise = undefined
|
||||||
listeners.disconnect.forEach(cb => cb())
|
listeners.disconnect.forEach(cb => cb())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,6 +189,8 @@ export function relayInit(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
return connectionPromise
|
||||||
}
|
}
|
||||||
|
|
||||||
function connected() {
|
function connected() {
|
||||||
|
|||||||
Reference in New Issue
Block a user