mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
feat: add beforeSend hook to sub()
This commit is contained in:
committed by
fiatjaf
parent
c236e41f80
commit
727bcb05a8
16
pool.js
16
pool.js
@@ -26,27 +26,35 @@ export function relayPool() {
|
||||
|
||||
const activeSubscriptions = {}
|
||||
|
||||
const sub = ({cb, filter}, id = Math.random().toString().slice(2)) => {
|
||||
const sub = (
|
||||
{cb, filter, beforeSend},
|
||||
id = Math.random().toString().slice(2)
|
||||
) => {
|
||||
const subControllers = Object.fromEntries(
|
||||
Object.values(relays)
|
||||
.filter(({policy}) => policy.read)
|
||||
.map(({relay}) => [
|
||||
relay.url,
|
||||
relay.sub({filter, cb: event => cb(event, relay.url)}, id)
|
||||
relay.sub({filter, cb: event => cb(event, relay.url), beforeSend}, id)
|
||||
])
|
||||
)
|
||||
|
||||
const activeCallback = cb
|
||||
const activeFilters = filter
|
||||
const activeBeforeSend = beforeSend
|
||||
|
||||
const unsub = () => {
|
||||
Object.values(subControllers).forEach(sub => sub.unsub())
|
||||
delete activeSubscriptions[id]
|
||||
}
|
||||
const sub = ({cb = activeCallback, filter = activeFilters}) => {
|
||||
const sub = ({
|
||||
cb = activeCallback,
|
||||
filter = activeFilters,
|
||||
beforeSend = activeBeforeSend
|
||||
}) => {
|
||||
Object.entries(subControllers).map(([relayURL, sub]) => [
|
||||
relayURL,
|
||||
sub.sub({cb, filter}, id)
|
||||
sub.sub({cb, filter, beforeSend}, id)
|
||||
])
|
||||
return activeSubscriptions[id]
|
||||
}
|
||||
|
||||
18
relay.js
18
relay.js
@@ -119,7 +119,10 @@ export function relayConnect(url, onNotice = () => {}, onError = () => {}) {
|
||||
ws.send(msg)
|
||||
}
|
||||
|
||||
const sub = ({cb, filter}, channel = Math.random().toString().slice(2)) => {
|
||||
const sub = (
|
||||
{cb, filter, beforeSend},
|
||||
channel = Math.random().toString().slice(2)
|
||||
) => {
|
||||
var filters = []
|
||||
if (Array.isArray(filter)) {
|
||||
filters = filter
|
||||
@@ -127,16 +130,25 @@ export function relayConnect(url, onNotice = () => {}, onError = () => {}) {
|
||||
filters.push(filter)
|
||||
}
|
||||
|
||||
if (beforeSend) {
|
||||
const beforeSendResult = beforeSend({filter, relay: url, channel})
|
||||
filters = beforeSendResult.filter
|
||||
}
|
||||
|
||||
trySend(['REQ', channel, ...filters])
|
||||
channels[channel] = cb
|
||||
openSubs[channel] = filters
|
||||
|
||||
const activeCallback = cb
|
||||
const activeFilters = filters
|
||||
const activeBeforeSend = beforeSend
|
||||
|
||||
return {
|
||||
sub: ({cb = activeCallback, filter = activeFilters}) =>
|
||||
sub({cb, filter}, channel),
|
||||
sub: ({
|
||||
cb = activeCallback,
|
||||
filter = activeFilters,
|
||||
beforeSend = activeBeforeSend
|
||||
}) => sub({cb, filter, beforeSend}, channel),
|
||||
unsub: () => {
|
||||
delete openSubs[channel]
|
||||
delete channels[channel]
|
||||
|
||||
Reference in New Issue
Block a user