Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | 5x 5x 5x 5x 5x 164x 164x 164x 5x 42x 42x 42x 164x 42x 42x 42x 5x | import { flatMap } from "lodash";
export interface IEventData<T = any> {
name: string;
data: T;
}
export type IEventFilter = (event: IEventData) => boolean;
export type IEventHandler<T = any> = (eventData: IEventData<T>) => boolean | void | Promise<boolean> | Promise<void>;
export interface ISubscription {
filter: IEventFilter;
handler: IEventHandler;
}
export interface ISubscriptionResult {
unsubscribe: () => boolean;
}
const subscriptions: ISubscription[] = [];
export function subscribe<T = any>(
nameOrFilter: string | IEventFilter,
handler: IEventHandler<T>
): ISubscriptionResult {
Iif (typeof nameOrFilter === "string") {
const name = nameOrFilter;
nameOrFilter = (evt) => evt.name === name;
}
const filter = nameOrFilter;
const subscription: ISubscription = {
filter,
handler,
};
subscriptions.push(subscription);
return {
unsubscribe: () => {
const iSub = subscriptions.indexOf(subscription);
Iif (iSub >= 0) {
subscriptions.splice(iSub, 1);
return true;
}
return false;
},
};
}
export function subscribeDebounce<T = any>(
nameOrFilter: string | IEventFilter,
handler: IEventHandler<T>,
debounceMs: number
): ISubscriptionResult {
let pid: any;
const handlerDebounced: IEventHandler = (evt) => {
Iif (pid) {
clearTimeout(pid);
}
pid = setTimeout(() => {
pid = 0;
handler(evt);
}, debounceMs);
};
return subscribe(nameOrFilter, handlerDebounced);
}
export async function emit(event: IEventData): Promise<boolean> {
const matchedHandlerPromises = subscriptions
.filter((subscription) => subscription.filter(event))
.map(async (subscription) => {
try {
return await subscription.handler(event);
} catch (err) {
console.error(
`An unhandled error occurred in a handler while processing event: ${JSON.stringify({ event, subscription })}`
);
return false;
}
});
const results = await Promise.all(matchedHandlerPromises);
// if any handlers returned false (or errored), return false, otherwise return true
return !results.some((r) => r === false);
}
// TODO probably comment this out or put behind a debug flag
// subscribe to all events and log them out
// subscribe(
// () => true,
// (evt) => {
// console.log(`event published: ${evt.name}`, { eventName: evt.name, data: evt.data });
// }
// );
export type IHandler<T> = (data: T) => boolean | void | Promise<boolean> | Promise<void>;
export interface IEvent<T> {
eventName: () => string;
subscribe: (handler: IHandler<T>) => ISubscriptionResult;
next: () => Promise<T>;
union: <U>(event: IEvent<U>) => IEvent<T | U>;
}
export class Event<T> implements IEvent<T> {
constructor(readonly _eventName: string) {
Iif (_eventName.includes("|")) {
throw new Error(`Do not use pipes in event names, they are reserved for union events`);
}
}
eventName = () => this._eventName;
public emit(data: T) {
return emit({
name: this._eventName,
data,
});
}
subscribe = (handler: IHandler<T>, debounceMs?: number) => {
const rawHandler: IEventHandler<T> = (evt: IEventData<T>) => handler(evt.data);
if (typeof debounceMs !== "number") {
return subscribe(this._eventName, rawHandler);
} else {
return subscribeDebounce(this._eventName, rawHandler, debounceMs);
}
};
next: () => Promise<T> = () =>
new Promise((resolve) => {
const sub = this.subscribe((evt) => {
sub.unsubscribe();
resolve(evt);
});
});
union: <U>(event: IEvent<U>) => IEvent<T | U> = (event) => unionEvents(this, event);
}
export function unionEvents(...events: IEvent<any>[]): IEvent<any> {
const eventName = events.map((s) => s.eventName()).join("|");
return {
eventName: () => eventName,
next: () => Promise.race(events.map((s) => s.next())),
subscribe: (handler) =>
subscribe(
(evt) => flatMap(events, (s) => s.eventName().split("|")).includes(evt.name),
(evt) => handler(evt)
),
union: unionEvents,
};
}
|