diff options
author | lonkaars <loek@pipeframe.xyz> | 2024-03-18 15:12:34 +0100 |
---|---|---|
committer | lonkaars <loek@pipeframe.xyz> | 2024-03-18 15:12:34 +0100 |
commit | c13e5adad9dbbc3ab45461099c65c16b5873c760 (patch) | |
tree | f6f1e967117d1e1ac20427154aa466e6aa0a55fd /ui/js | |
parent | 10bb8f597f92df37b2cb500b4a88821a7bfa7629 (diff) |
beginel JS gedoe
Diffstat (limited to 'ui/js')
-rw-r--r-- | ui/js/api.js | 17 | ||||
-rw-r--r-- | ui/js/main.js | 5 | ||||
-rw-r--r-- | ui/js/socket.js | 19 |
3 files changed, 41 insertions, 0 deletions
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); +}; + |