Skip to content

Commit

Permalink
Added a global ConnectionService
Browse files Browse the repository at this point in the history
  • Loading branch information
Frederick Behringer committed Feb 20, 2024
1 parent 662407f commit 534e37e
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 106 deletions.
113 changes: 113 additions & 0 deletions frontend-vue/src/services/ConnectionService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { ref } from 'vue';
import { useWebSocketStore } from '@/stores/webSocketStore';
import { useRouter, type Router } from 'vue-router';
import type { Room } from '@/model/room';
import { useCookies } from '@vueuse/integrations/useCookies';


let router: Router;
let store: any;
const cookies = useCookies(['username', 'roomId', 'userId']);

export let room = ref<Room>();
export let you = ref();


/**
* Tests if we already have a Websocket Connection otherwise tries to reconnect
*/
export function testConnection() {
if (!store) {
store = useWebSocketStore();
router = useRouter();
}
// maybe we need to reconnect
if (!store.webSocket || store.webSocket === null) {
connect();
} else {
// wait with init function until websocket connection was confirmed
init();
}
}

/**
* Handles a connection or reconnection
*/
export function connect() {
let roomId = router.currentRoute.value.query.roomId || cookies.get('roomId');
let userId = cookies.get('userId');
let name = cookies.get('username');

store.changeWebSocket(new WebSocket(`${import.meta.env.VITE_BACKEND_ENDPOINT}?name=${name}&roomId=${roomId}&userId=${userId}`));
const abortController = new AbortController();
store.webSocket.addEventListener('message', (event: MessageEvent) => {
const inLandingPage = router.currentRoute.value.name === 'landing-page';
const data = JSON.parse(event.data);
console.log(data);
if (data.action === 'connected') {
if (inLandingPage) {
cookies.set('userId', data.data.you.id);
cookies.set('roomId', data.data.roomId);
// navigate to lobby
router.push(`/lobby?roomId=${data.data.roomId}`)
} else {
init();
}
} else {
console.error('Could not join!');
if (!inLandingPage) { // redirect if we are not already there
router.push(`/?roomId=${data.data.roomId}`);
}
}
abortController.abort();
}, { signal: abortController.signal });
}

/**
* Starts the game, should only be callable if we are an admin.
*/
export function startGame() {
store.webSocket.send(JSON.stringify({ action: 'start' }));
}

/**
* Main stuff of setup
*/
export function init() {
store.webSocket.send(JSON.stringify({ action: 'getRoomInfo' }));
store.webSocket.addEventListener('message', (event : MessageEvent) => {
const data = JSON.parse(event.data);
console.log(data.action, data);
switch (data.action) {
case 'gotRoomInfo':
room.value = data.data;
you.value = data.data.you;
if (data.data.state === 'inGame') {
router.push(`/${data.data.selectedGame}?roomId=${data.data.roomId}`);
}
break;
case 'joined':
if (!room.value) return;
room.value.users.push(data.data.user);
break;
case 'disconnected':
var user = room.value?.users.find(user => user.id === data.data.id);
if (user) {
user.disconnected = true;
}
break;
case 'reconnected':
var user = room.value?.users.find(user => user.id === data.data.user.id);
if (user) {
user.disconnected = false;
console.log(user);
}
break;
case 'started':
case 'dealCards':
if (!room.value) return;
router.push(`/${room.value.selectedGame}?roomId=${data.data.roomId}`);
break;
}
});
}
27 changes: 3 additions & 24 deletions frontend-vue/src/views/LandingView.vue
Original file line number Diff line number Diff line change
@@ -1,35 +1,14 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useWebSocketStore } from '../stores/webSocketStore'
import { useCookies } from '@vueuse/integrations/useCookies'
import startButton from '@/components/startButton.vue'
import { connect } from '@/services/ConnectionService'
const router = useRouter()
const store = useWebSocketStore()
const cookies = useCookies(['username', 'roomId', 'userId'])
const cookies = useCookies(['username'])
let name = ref(cookies.get('username'))
function joinRoom() {
let roomId = router.currentRoute.value.query.roomId || cookies.get('roomId')
let userId = cookies.get('userId');
cookies.set('username', name.value);
store.changeWebSocket(new WebSocket(`${import.meta.env.VITE_BACKEND_ENDPOINT}?name=${name.value}&roomId=${roomId}&userId=${userId}`))
const abortController = new AbortController();
store.webSocket.addEventListener('message', (event: MessageEvent) => {
const data = JSON.parse(event.data)
console.log(data)
if (data.action === 'connected') {
cookies.set('userId', data.data.you.id);
cookies.set('roomId', data.data.roomId);
// navigate to lobby
router.push(`/lobby?roomId=${data.data.roomId}`)
abortController.abort();
} else {
console.error('Could not join!')
}
}, { signal: abortController.signal });
connect();
}
</script>

Expand Down
85 changes: 3 additions & 82 deletions frontend-vue/src/views/LobbyCreaterView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,91 +8,11 @@ import type { User } from '@/model/user'
import type { Room } from '@/model/room'
import { Game } from '@/model/room'
import { useCookies } from '@vueuse/integrations/useCookies'
const router = useRouter()
const store = useWebSocketStore()
const cookies = useCookies(['username', 'roomId', 'userId'])
import { you, room, testConnection, startGame } from '@/services/ConnectionService';
const games = Object.keys(Game).filter((key: any) => typeof Game[key] === 'number');
let room = ref<Room>()
// let users = ref([] as User[])
let you = ref()
let local = ref()
function reconnect() {
let roomId = router.currentRoute.value.query.roomId || cookies.get('roomId')
let userId = cookies.get('userId');
let name = cookies.get('username');
store.changeWebSocket(new WebSocket(`${import.meta.env.VITE_BACKEND_ENDPOINT}?name=${name}&roomId=${roomId}&userId=${userId}`))
const abortController = new AbortController();
store.webSocket.addEventListener('message', (event: MessageEvent) => {
const data = JSON.parse(event.data)
console.log(data)
if (data.action === 'connected') {
init();
} else {
console.error('Could not join!');
router.push(`/?roomId=${data.data.roomId}`)
}
abortController.abort();
}, { signal: abortController.signal });
}
function startGame() {
store.webSocket.send(JSON.stringify({ action: 'start' }));
}
/**
* Main stuff of setup
*/
function init() {
store.webSocket.send(JSON.stringify({ action: 'getRoomInfo' }));
store.webSocket.addEventListener('message', (event : MessageEvent) => {
const data = JSON.parse(event.data);
console.log(data.action, data)
switch (data.action) {
case 'gotRoomInfo':
room.value = data.data;
you.value = data.data.you;
if (data.data.state === 'inGame') {
router.push(`/${data.data.selectedGame}?roomId=${data.data.roomId}`)
}
break;
case 'joined':
if (!room.value) return;
room.value.users.push(data.data.user);
break;
case 'disconnected':
var user = room.value?.users.find(user => user.id === data.data.id);
if (user) {
user.disconnected = true;
}
break;
case 'reconnected':
var user = room.value?.users.find(user => user.id === data.data.user.id);
if (user) {
user.disconnected = false;
console.log(user)
}
break;
case 'started':
case 'dealCards':
if (!room.value) return;
router.push(`/${room.value.selectedGame}?roomId=${data.data.roomId}`)
break;
}
});
}
// maybe we need to reconnect
if (!store.webSocket || store.webSocket === null) {
reconnect();
} else {
// wait with init function until websocket connection was confirmed
init();
}
testConnection();
function copyToClipboard() {
navigator.clipboard.writeText(window.location.origin + window.location.search);
Expand Down Expand Up @@ -131,3 +51,4 @@ function copyToClipboard() {
</div>
</main>
</template>
@/services/ConnectionService

0 comments on commit 534e37e

Please sign in to comment.