@ -8,11 +8,12 @@ type SubCallback = (
type Subscribe = {
cb : SubCallback ;
filter : Filter ;
unsub? : boolean ;
} ;
const relayList : Array < Relay > = [ ] ;
const subList : Array < Sub > = [ ] ;
const currentSubList : Array < Subscribe > = [ ] ;
const relayMap = new Map < string , Relay > ( ) ;
export const addRelay = async ( url : string ) = > {
const relay = relayInit ( url ) ;
@ -25,13 +26,13 @@ export const addRelay = async (url: string) => {
try {
await relay . connect ( ) ;
currentSubList . forEach ( ( { cb , filter } ) = > subscribe ( cb , filter , relay ) ) ;
relay List. push ( relay ) ;
relay Map. set ( url , relay ) ;
} catch {
console . warn ( ` could not connect to ${ url } ` ) ;
}
} ;
const unsubscribe = ( sub : Sub ) = > {
export const unsubscribe = ( sub : Sub ) = > {
sub . unsub ( ) ;
subList . splice ( subList . indexOf ( sub ) , 1 ) ;
} ;
@ -40,28 +41,38 @@ const subscribe = (
cb : SubCallback ,
filter : Filter ,
relay : Relay ,
unsub? : boolean
) = > {
const sub = relay . sub ( [ filter ] ) ;
subList . push ( sub ) ;
sub . on ( 'event' , ( event : Event ) = > {
cb ( event , relay . url ) ;
} ) ;
if ( unsub ) {
sub . on ( 'eose' , ( ) = > {
// console.log('eose', relay.url);
// unsubscribe(sub);
console . log ( 'eose' , relay . url ) ;
unsubscribe ( sub ) ;
} ) ;
} ;
const subscribeAll = (
cb : SubCallback ,
filter : Filter ,
) = > {
relayList . forEach ( relay = > subscribe ( cb , filter , relay ) ) ;
}
return sub ;
} ;
export const sub = ( obj : Subscribe ) = > {
currentSubList . push ( obj ) ;
subscribeAll ( obj . cb , obj . filter ) ;
relayMap . forEach ( ( relay ) = > subscribe ( obj . cb , obj . filter , relay , obj . unsub ) ) ;
} ;
export const subOnce = (
obj : Subscribe & { relay : string }
) = > {
const relay = relayMap . get ( obj . relay ) ;
if ( relay ) {
const sub = subscribe ( obj . cb , obj . filter , relay ) ;
sub . on ( 'eose' , ( ) = > {
console . log ( 'eose' , obj . relay ) ;
unsubscribe ( sub ) ;
} ) ;
}
} ;
export const unsubAll = ( ) = > {
@ -78,7 +89,7 @@ export const publish = (
event : Event ,
cb : PublishCallback ,
) = > {
relay List. forEach ( relay = > {
relay Map. forEach ( ( relay , url ) = > {
const pub = relay . publish ( event ) ;
pub . on ( 'ok' , ( ) = > {
console . info ( ` ${ relay . url } has accepted our event ` ) ;
@ -91,9 +102,10 @@ export const publish = (
} ) ;
} ;
addRelay ( 'wss://relay.snort.social' ) ; // good one
addRelay ( 'wss://relay.snort.social' ) ;
addRelay ( 'wss://nostr.bitcoiner.social' ) ;
addRelay ( 'wss://nostr.mom' ) ;
addRelay ( 'wss://relay.nostr.bg' ) ;
addRelay ( 'wss://nos.lol' ) ;
addRelay ( 'wss://relay.nostr.ch' ) ;
// addRelay('wss://relay.nostr.ch');