Last active
February 23, 2023 17:38
-
-
Save nestarz/43e8b0fc85d03f0d50c82c38b1d1b5b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type EventTargetWithAddListener = EventTarget & { | |
listeners: Map<string, any>; | |
addEventListener( | |
type: string, | |
listeners: Map<string, (event: Event) => any>, | |
options?: boolean | AddEventListenerOptions | |
): void; | |
}; | |
export const handleEventEmitter = ( | |
target: EventTarget, | |
previous?: EventTargetWithAddListener | |
): EventTargetWithAddListener => { | |
const proxy = (fn, originalMethod) => | |
function (...args: any[]) { | |
return fn(...args), originalMethod.apply(this, args); | |
}; | |
const listeners = new Map(); | |
const handler = { | |
get: (obj: any, prop: string, value: any) => | |
prop === "listeners" | |
? listeners | |
: prop === "addEventListener" | |
? proxy((...a) => listeners.set(a, a), obj[prop]) | |
: prop === "removeEventListener" | |
? proxy((...a) => listeners.delete(a), obj[prop]) | |
: Reflect.get(obj, prop, value), | |
}; | |
const newTarget = new Proxy(target, handler); | |
for (const [_, [key, value]] of previous?.listeners ?? []) | |
newTarget.addEventListener(key, value); | |
return newTarget; | |
}; | |
export default ( | |
wss: Record<string, WebSocket>, | |
timeout = 5000, | |
reapplyEvents = true | |
) => { | |
Object.keys(wss).forEach((key) => { | |
wss[key] = reapplyEvents ? handleEventEmitter(wss[key]) : wss[key]; | |
wss[key].binaryType = "arraybuffer"; | |
wss[key].addEventListener("open", () => console.log(`${key} is opened`)); | |
wss[key].addEventListener("close", () => { | |
console.warn(`${key} has closed, reopening in ${timeout}ms`); | |
setTimeout(() => { | |
wss[key] = reapplyEvents | |
? handleEventEmitter(new WebSocket(wss[key].url), wss[key]) | |
: new WebSocket(wss[key].url); | |
wss[key].binaryType = "arraybuffer"; | |
}, timeout); | |
}); | |
}); | |
return wss; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment