diff options
author | Hayleigh Thompson <me@hayleigh.dev> | 2023-08-23 23:09:16 +0100 |
---|---|---|
committer | Hayleigh Thompson <me@hayleigh.dev> | 2023-08-23 23:09:16 +0100 |
commit | c0a3607d41dd24b9ea03425892a361261893d076 (patch) | |
tree | 7387b86b55e48649aa5afb45df37193d72aa930b /compat/lustre_websocket/src/ffi.mjs | |
parent | 21d59712dd56909293b3804b1d89320216f6906a (diff) | |
download | lustre-c0a3607d41dd24b9ea03425892a361261893d076.tar.gz lustre-c0a3607d41dd24b9ea03425892a361261893d076.zip |
:ambulance: Update third-party lustre_websocket package to new api.
Diffstat (limited to 'compat/lustre_websocket/src/ffi.mjs')
-rw-r--r-- | compat/lustre_websocket/src/ffi.mjs | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/compat/lustre_websocket/src/ffi.mjs b/compat/lustre_websocket/src/ffi.mjs new file mode 100644 index 0000000..56f11fd --- /dev/null +++ b/compat/lustre_websocket/src/ffi.mjs @@ -0,0 +1,39 @@ +let ws_handler_registry = {} + +export const init_websocket = path => { + let ws + if (typeof WebSocket === "function") { + // we're in the browser + let url = new URL(document.URL) + let protocol = url.protocol === "http:" ? "ws" : "wss" + let ws_url = protocol + "://" + url.host + url.pathname + path + ws = new WebSocket(ws_url) + } else { + // we're NOT in the browser, prolly running tests + ws = {} + } + ws_handler_registry[ws.url] = { ws: ws } + + ws.onopen = evt => { + ws_handler_registry[ws.url]?.on_open?.() + } + ws.onclose = evt => { + ws_handler_registry[ws.url]?.on_close?.(evt.code) + delete ws_handler_registry[ws.url] + } + ws.onmessage = event => ws_handler_registry[ws.url]?.on_message?.(event.data) + ws.onerror = error => console.log("ws", ws.url, "error", error, "no handler, since I have no clue what errors we might be talking about") + return ws +} + +export const register_websocket_handler = (ws, on_open, on_message, on_close) => { + const reg_entry = ws_handler_registry[ws.url] + reg_entry.on_open = on_open + reg_entry.on_message = on_message + reg_entry.on_close = on_close + console.log("ws reg", ws_handler_registry) +} + +export const send_over_websocket = (ws, msg) => { + ws.send(msg) +} |