From 1f101fe7cc5cc31c66146a1e226fa4bae805fdd4 Mon Sep 17 00:00:00 2001
From: Leonardo Bishop <me@leonardobishop.com>
Date: Thu, 9 Nov 2023 00:17:03 +0000
Subject: Refactor websockets

---
 frontend/src/views/HostView.vue | 57 ++++++++++++++++-------------------------
 1 file changed, 22 insertions(+), 35 deletions(-)

(limited to 'frontend/src/views/HostView.vue')

diff --git a/frontend/src/views/HostView.vue b/frontend/src/views/HostView.vue
index 8d6a6b9..adc9c05 100644
--- a/frontend/src/views/HostView.vue
+++ b/frontend/src/views/HostView.vue
@@ -16,46 +16,33 @@ function startGame() {
     return;
   }
   socket.send(JSON.stringify({
-    action: 'start',
-    sessionId: code.value,
+    type: 'start',
+    payload: {}
   }));
 }
 
-fetch(`${import.meta.env.VITE_BACKEND_BASE_URL}/session`,
-  {
-    method: 'POST',
-    headers: {
-      'Content-Type': 'application/json'
-    },
-  }
-).then(async (response) => {
-  const data: any = await response.json();
-  code.value = data.id;
-  url.value = `${import.meta.env.VITE_FRONTEND_BASE_URL}/join/${data.id}`;
-  waitingForCode.value = false;
-  openSocket(data.id);
-});
+socket = new WebSocket(`${import.meta.env.VITE_BACKEND_WS_URL}/coop?action=create`);
 
-function openSocket(id: string) {
-  socket = new WebSocket(`${import.meta.env.VITE_BACKEND_WS_URL}`);
+socket.onmessage = (event) => {
+  const data = JSON.parse(event.data);
+  const type = data.type;
+  const payload = data.payload;
 
-  socket.onopen = () => {
-    socket.send(JSON.stringify({
-      action: 'host',
-      sessionId: id,
-    }));
-  };
-  socket.onmessage = (event) => {
-    const data = JSON.parse(event.data);
-    if (data.action === 'join') {
-      numClients.value = data.clients;
-    } else if (data.action === 'state' && data.state === 'playing') {
-      started.value = true;
-    } else if (data.action === 'move') {
-      inputQueue.value.push(data.move);
-    }
-  };
-}
+  if (type === 'create') {
+    code.value = payload.sessionId;
+    waitingForCode.value = false;
+    url.value = `${import.meta.env.VITE_FRONTEND_BASE_URL}/join/${payload.sessionId}`;
+
+  } else if (type === 'join') {
+    numClients.value = payload.numberOfClients;
+
+  } else if (type === 'state') {
+    started.value = payload.state === 'playing';
+
+  } else if (type === 'move') {
+    inputQueue.value.push(payload.move);
+  }
+};
 </script>
 
 <template>
-- 
cgit v1.2.3-70-g09d2

