diff --git a/nip42.ts b/nip42.ts index 3df325a..cd873a9 100644 --- a/nip42.ts +++ b/nip42.ts @@ -28,14 +28,14 @@ export const authenticate = async ({ ], content: '' } - const sub = relay.publish(await sign(e), 'AUTH') + const pub = relay.auth(await sign(e)) return new Promise((resolve, reject) => { - sub.on('ok', function ok() { - sub.off('ok', ok) + pub.on('ok', function ok() { + pub.off('ok', ok) resolve() }) - sub.on('failed', function fail(reason: string) { - sub.off('failed', fail) + pub.on('failed', function fail(reason: string) { + pub.off('failed', fail) reject(reason) }) }) diff --git a/relay.ts b/relay.ts index 68265a4..17d59d5 100644 --- a/relay.ts +++ b/relay.ts @@ -4,7 +4,6 @@ import {Event, verifySignature, validateEvent} from './event' import {Filter, matchFilters} from './filter' import {getHex64, getSubscriptionId} from './fakejson' -type OutgoingEventType = 'EVENT' | 'AUTH' type RelayEvent = { connect: () => void | Promise disconnect: () => void | Promise @@ -32,7 +31,8 @@ export type Relay = { filters: Filter[], opts?: SubscriptionOptions ) => Promise - publish: (event: Event, type?: OutgoingEventType) => Pub + publish: (event: Event) => Pub + auth: (event: Event) => Pub off: ( event: T, listener: U @@ -179,7 +179,7 @@ export function relayInit( let id = data[1] let payload = data[2] if (openSubs[id]) { - (subListeners[id]?.count || []).forEach(cb => cb(payload)) + ;(subListeners[id]?.count || []).forEach(cb => cb(payload)) } return case 'EOSE': { @@ -298,6 +298,29 @@ export function relayInit( } } + function _publishEvent(event: Event, type: string) { + if (!event.id) throw new Error(`event ${event} has no id`) + let id = event.id + + trySend([type, event]) + + return { + on: (type: 'ok' | 'failed', cb: any) => { + pubListeners[id] = pubListeners[id] || { + ok: [], + failed: [] + } + pubListeners[id][type].push(cb) + }, + off: (type: 'ok' | 'failed', cb: any) => { + let listeners = pubListeners[id] + if (!listeners) return + let idx = listeners[type].indexOf(cb) + if (idx >= 0) listeners[type].splice(idx, 1) + } + } + } + return { url, sub, @@ -364,27 +387,11 @@ export function relayInit( resolve(event) }) }), - publish(event, type = 'EVENT'): Pub { - if (!event.id) throw new Error(`event ${event} has no id`) - let id = event.id - - trySend([type, event]) - - return { - on: (type: 'ok' | 'failed', cb: any) => { - pubListeners[id] = pubListeners[id] || { - ok: [], - failed: [] - } - pubListeners[id][type].push(cb) - }, - off: (type: 'ok' | 'failed', cb: any) => { - let listeners = pubListeners[id] - if (!listeners) return - let idx = listeners[type].indexOf(cb) - if (idx >= 0) listeners[type].splice(idx, 1) - } - } + publish(event): Pub { + return _publishEvent(event, 'EVENT') + }, + auth(event): Pub { + return _publishEvent(event, 'AUTH') }, connect, close(): void {