guard against some nonexisting arrays of event listeners.

This commit is contained in:
fiatjaf
2022-12-23 15:15:19 -03:00
parent c0d1e41424
commit 74a0d5454a
2 changed files with 12 additions and 9 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "nostr-tools", "name": "nostr-tools",
"version": "1.0.0-rc1", "version": "1.0.0-rc2",
"description": "Tools for making a Nostr client.", "description": "Tools for making a Nostr client.",
"repository": { "repository": {
"type": "git", "type": "git",

View File

@@ -98,13 +98,13 @@ export function relayInit(url: string): Relay {
matchFilters(openSubs[id].filters, event) matchFilters(openSubs[id].filters, event)
) { ) {
openSubs[id] openSubs[id]
subListeners[id]?.event.forEach(cb => cb(event)) ;(subListeners[id]?.event || []).forEach(cb => cb(event))
} }
return return
case 'EOSE': { case 'EOSE': {
if (data.length !== 2) return // ignore empty or malformed EOSE if (data.length !== 2) return // ignore empty or malformed EOSE
let id = data[1] let id = data[1]
subListeners[id]?.eose.forEach(cb => cb()) ;(subListeners[id]?.eose || []).forEach(cb => cb())
return return
} }
case 'OK': { case 'OK': {
@@ -174,8 +174,9 @@ export function relayInit(url: string): Relay {
subListeners[subid][type].push(cb) subListeners[subid][type].push(cb)
}, },
off: (type: 'event' | 'eose', cb: any): void => { off: (type: 'event' | 'eose', cb: any): void => {
let idx = subListeners[subid][type].indexOf(cb) let listeners = subListeners[subid]
if (idx >= 0) subListeners[subid][type].splice(idx, 1) let idx = listeners[type].indexOf(cb)
if (idx >= 0) listeners[type].splice(idx, 1)
} }
} }
} }
@@ -221,14 +222,14 @@ export function relayInit(url: string): Relay {
id: `monitor-${id.slice(0, 5)}` id: `monitor-${id.slice(0, 5)}`
}) })
let willUnsub = setTimeout(() => { let willUnsub = setTimeout(() => {
pubListeners[id].failed.forEach(cb => ;(pubListeners[id]?.failed || []).forEach(cb =>
cb('event not seen after 5 seconds') cb('event not seen after 5 seconds')
) )
monitor.unsub() monitor.unsub()
}, 5000) }, 5000)
monitor.on('event', () => { monitor.on('event', () => {
clearTimeout(willUnsub) clearTimeout(willUnsub)
pubListeners[id].seen.forEach(cb => cb()) ;(pubListeners[id]?.seen || []).forEach(cb => cb())
}) })
} }
@@ -247,8 +248,10 @@ export function relayInit(url: string): Relay {
} }
}, },
off: (type: 'ok' | 'seen' | 'failed', cb: any) => { off: (type: 'ok' | 'seen' | 'failed', cb: any) => {
let idx = pubListeners[id][type].indexOf(cb) let listeners = pubListeners[id]
if (idx >= 0) pubListeners[id][type].splice(idx, 1) if (!listeners) return
let idx = listeners[type].indexOf(cb)
if (idx >= 0) listeners[type].splice(idx, 1)
} }
} }
}, },