-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathon-event-filters.ts
63 lines (57 loc) · 1.74 KB
/
on-event-filters.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
import {type Filter, Kind, matchFilter, type Event} from "nostr-tools";
import type {EventObject} from "./event";
export type OnEventArgs = [
event: Event,
afterEose: boolean,
url: string | undefined
];
export type OnEvent = (
event: Event,
afterEose: boolean,
url: string | undefined
) => void;
export type OnEventObject = (
eventObject: EventObject,
afterEose: boolean,
url: string | undefined
) => void;
export function doNotEmitDuplicateEvents(onEvent: OnEvent): OnEvent {
let event_ids = new Set();
return (event: Event, afterEose: boolean, url: string | undefined) => {
if (event_ids.has(event.id)) return;
event_ids.add(event.id);
onEvent(event, afterEose, url);
};
}
export function doNotEmitOlderEvents(onEvent: OnEvent): OnEvent {
let created_at_by_events_kinds = new Map();
return (event: Event, afterEose: boolean, url: string | undefined) => {
if (event.kind === Kind.Metadata || event.kind === Kind.Contacts) {
let event_kind = event.pubkey + " " + event.kind;
if ((created_at_by_events_kinds.get(event_kind) || 0) > event.created_at)
return;
created_at_by_events_kinds.set(event_kind, event.created_at);
}
onEvent(event, afterEose, url);
};
}
export function matchOnEventFilters(
onEvent: OnEvent,
filters: Filter[]
): OnEvent {
return (event: Event, afterEose: boolean, url: string | undefined) => {
for (let filter of filters) {
if (matchFilter(filter, event)) {
onEvent(event, afterEose, url);
break;
}
}
};
}
export function emitEventsOnNextTick(onEvent: OnEvent): OnEvent {
return (event: Event, afterEose: boolean, url: string | undefined) => {
setTimeout(() => {
onEvent(event, afterEose, url);
}, 0);
};
}