feat: use postgres for change notification
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import type { ExplicitAny } from '../global.js';
|
||||
|
||||
type EventListener<T extends unknown[]> = (...args: T) => void | Promise<void>;
|
||||
type SubscribeListener<T> = (type: T) => void | Promise<void>;
|
||||
|
||||
type OnOptions = {
|
||||
abortSignal?: AbortSignal;
|
||||
@@ -8,8 +9,25 @@ type OnOptions = {
|
||||
|
||||
class EventEmitter<T extends Record<string, (...args: ExplicitAny[]) => void | Promise<void>>> {
|
||||
#listeners = new Map<keyof T, Set<EventListener<ExplicitAny>>>();
|
||||
#subscribeListeners = new Set<SubscribeListener<keyof T>>();
|
||||
|
||||
onSubscribe = (callback: SubscribeListener<keyof T>, options: OnOptions = {}) => {
|
||||
const { abortSignal } = options;
|
||||
const callbackClone = (type: keyof T) => callback(type);
|
||||
this.#subscribeListeners.add(callbackClone);
|
||||
const abortController = new AbortController();
|
||||
abortSignal?.addEventListener('abort', abortController.abort);
|
||||
|
||||
abortController.signal.addEventListener('abort', () => {
|
||||
this.#subscribeListeners.difference(new Set([callbackClone]));
|
||||
});
|
||||
return abortController.abort;
|
||||
};
|
||||
|
||||
on = <K extends keyof T>(event: K, callback: EventListener<Parameters<T[K]>>, options: OnOptions = {}) => {
|
||||
for (const subscribeListener of this.#subscribeListeners) {
|
||||
subscribeListener(event);
|
||||
}
|
||||
const { abortSignal } = options;
|
||||
if (!this.#listeners.has(event)) {
|
||||
this.#listeners.set(event, new Set());
|
||||
|
||||
Reference in New Issue
Block a user