From c13e5adad9dbbc3ab45461099c65c16b5873c760 Mon Sep 17 00:00:00 2001 From: lonkaars Date: Mon, 18 Mar 2024 15:12:34 +0100 Subject: beginel JS gedoe --- ui/js/api.js | 17 +++++++++++++++++ ui/js/main.js | 5 +++++ ui/js/socket.js | 19 +++++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 ui/js/api.js create mode 100644 ui/js/main.js create mode 100644 ui/js/socket.js (limited to 'ui/js') diff --git a/ui/js/api.js b/ui/js/api.js new file mode 100644 index 0000000..5fca3cf --- /dev/null +++ b/ui/js/api.js @@ -0,0 +1,17 @@ +import ws from './socket.js'; + +export default { + msg: { + send: { + helloWorld: () => { + ws.send(JSON.stringify({res: 'OK'})); + } + }, + handle: { + helloWorld: msg => { + console.log(msg); + }, + }, + }, +}; + diff --git a/ui/js/main.js b/ui/js/main.js new file mode 100644 index 0000000..033b0bb --- /dev/null +++ b/ui/js/main.js @@ -0,0 +1,5 @@ +import './socket.js'; + +import api from './api.js'; +window.api = api; // export api to inline JS handlers + diff --git a/ui/js/socket.js b/ui/js/socket.js new file mode 100644 index 0000000..46edb8d --- /dev/null +++ b/ui/js/socket.js @@ -0,0 +1,19 @@ +import api from './api.js'; + +var ws = new WebSocket('ws://localhost:8081/socket'); +export default ws; + +ws.onmessage = ev => { + // this will already throw an error if the message doesn't contain valid JSON + const msg = JSON.parse(ev.data); + + // check if api.msg.handle has a handler for msg.type + if (!api.msg.handle.hasOwnProperty(msg.type)) { + console.warn(`No message handler for type ${msg.type}`, msg); + return; + } + + // run the appropriate message handler + api.msg.handle[msg.type](msg); +}; + -- cgit v1.2.3