type Relay EventHandler (#121)

* type Relay EventHandler

* Update relay.ts
This commit is contained in:
BilligsterUser
2023-03-11 19:24:52 +01:00
committed by GitHub
parent b00af9a30a
commit d244b62c7a

View File

@@ -4,7 +4,12 @@ import {Event, verifySignature, validateEvent} from './event'
import {Filter, matchFilters} from './filter' import {Filter, matchFilters} from './filter'
import {getHex64, getSubscriptionId} from './fakejson' import {getHex64, getSubscriptionId} from './fakejson'
type RelayEvent = 'connect' | 'disconnect' | 'error' | 'notice' type RelayEvent = {
connect: () => void
disconnect: () => void
error: () => void
notice: (msg: string) => void
}
export type Relay = { export type Relay = {
url: string url: string
@@ -15,8 +20,8 @@ export type Relay = {
list: (filters: Filter[], opts?: SubscriptionOptions) => Promise<Event[]> list: (filters: Filter[], opts?: SubscriptionOptions) => Promise<Event[]>
get: (filter: Filter, opts?: SubscriptionOptions) => Promise<Event | null> get: (filter: Filter, opts?: SubscriptionOptions) => Promise<Event | null>
publish: (event: Event) => Pub publish: (event: Event) => Pub
on: (type: RelayEvent, cb: any) => void off: <T extends keyof RelayEvent, U extends RelayEvent[T]>(event: T, listener: U) => void
off: (type: RelayEvent, cb: any) => void on: <T extends keyof RelayEvent, U extends RelayEvent[T]>(event: T, listener: U) => void
} }
export type Pub = { export type Pub = {
on: (type: 'ok' | 'failed', cb: any) => void on: (type: 'ok' | 'failed', cb: any) => void
@@ -46,12 +51,7 @@ export function relayInit(
var ws: WebSocket var ws: WebSocket
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {} var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
var listeners: { var listeners: { [TK in keyof RelayEvent]: RelayEvent[TK][]} = {
connect: Array<() => void>
disconnect: Array<() => void>
error: Array<() => void>
notice: Array<(msg: string) => void>
} = {
connect: [], connect: [],
disconnect: [], disconnect: [],
error: [], error: [],
@@ -242,14 +242,15 @@ export function relayInit(
return { return {
url, url,
sub, sub,
on: (type: RelayEvent, cb: any): void => { on: <T extends keyof RelayEvent, U extends RelayEvent[T]>(type: T, cb: U): void => {
listeners[type].push(cb) listeners[type].push(cb)
if (type === 'connect' && ws?.readyState === 1) { if (type === 'connect' && ws?.readyState === 1) {
cb() // i would love to know why we need this
} (cb as ()=> void)()
}, }
off: (type: RelayEvent, cb: any): void => { },
off: <T extends keyof RelayEvent, U extends RelayEvent[T]>(type: T, cb: U): void => {
let index = listeners[type].indexOf(cb) let index = listeners[type].indexOf(cb)
if (index !== -1) listeners[type].splice(index, 1) if (index !== -1) listeners[type].splice(index, 1)
}, },