-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathevent-demultiplexer.ts
75 lines (71 loc) · 2.27 KB
/
event-demultiplexer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {type Filter, matchFilter, type Event} from "nostr-tools";
import type {OnEvent} from "./on-event-filters";
export class EventDemultiplexer {
filterAndOnEventByEvent: Map<string, [Filter, OnEvent][]> = new Map();
#addEventUsingEventKey(
event: Event,
afterEose: boolean,
url: string | undefined,
eventKey: string
) {
const filterAndOnEvent = this.filterAndOnEventByEvent.get(eventKey);
if (filterAndOnEvent) {
for (const [filter, onEvent] of filterAndOnEvent) {
if (matchFilter(filter, event)) {
onEvent(event, afterEose, url);
}
}
}
}
onEvent(event: Event, afterEose: boolean, url: string | undefined) {
this.#addEventUsingEventKey(event, afterEose, url, `ids:${event.id}`);
this.#addEventUsingEventKey(
event,
afterEose,
url,
`authors:${event.pubkey}`
);
for (const tag of event.tags) {
this.#addEventUsingEventKey(
event,
afterEose,
url,
`#${tag[0]}:${tag[1]}`
);
}
this.#addEventUsingEventKey(event, afterEose, url, `kinds:${event.kind}`);
this.#addEventUsingEventKey(event, afterEose, url, "");
}
subscribe(filters: Filter[], onEvent: OnEvent) {
for (const filter of filters) {
let added = false;
for (const key of ["ids", "authors", ...filterTags(filter), "kinds"]) {
if (key in filter) {
// @ts-ignore
for (const value of filter[key]) {
const eventKey = `${key}:${value}`;
const filterAndOnEvent = this.filterAndOnEventByEvent.get(eventKey);
if (filterAndOnEvent) {
filterAndOnEvent.push([filter, onEvent]);
} else {
this.filterAndOnEventByEvent.set(eventKey, [[filter, onEvent]]);
}
}
added = true;
break;
}
}
if (!added) {
const eventKey = "";
const filterAndOnEvent = this.filterAndOnEventByEvent.get(eventKey);
if (filterAndOnEvent) {
filterAndOnEvent.push([filter, onEvent]);
} else {
this.filterAndOnEventByEvent.set(eventKey, [[filter, onEvent]]);
}
}
}
}
}
const filterTags = (filter: Filter): string[] =>
Object.keys(filter).filter((key) => key.startsWith("#"));