forked from noxious/client
New login design, added basic logic for multiplayer (WIP)
This commit is contained in:
66
src/stores/socket.ts
Normal file
66
src/stores/socket.ts
Normal file
@ -0,0 +1,66 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
import config from '@/config';
|
||||
import axios from 'axios';
|
||||
|
||||
export const useSocketStore = defineStore('socket', {
|
||||
state: () => ({
|
||||
isAuthenticated: false,
|
||||
socket: null as Socket | null,
|
||||
}),
|
||||
|
||||
actions: {
|
||||
async register(username: string, password: string) {
|
||||
if ( this.isAuthenticated ) return console.log('User already authenticated');
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${config.server_endpoint}/register`, { username, password });
|
||||
console.log(response.data);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error registering user:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
async login(username: string, password: string) {
|
||||
if ( this.isAuthenticated ) return console.log('User already authenticated');
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${config.server_endpoint}/login`, { username, password });
|
||||
if (response.status === 200) {
|
||||
this.isAuthenticated = true;
|
||||
this.setupSocketConnection(username, password);
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
setupSocketConnection(username: string, password: string) {
|
||||
this.socket = io(config.server_endpoint as string, {
|
||||
query: { username, password },
|
||||
transports: ['websocket']
|
||||
});
|
||||
|
||||
this.socket.on('connect', () => {
|
||||
console.log('Socket connected!');
|
||||
});
|
||||
|
||||
this.socket.on('message', (message) => {
|
||||
console.log('Received message:', message);
|
||||
});
|
||||
|
||||
// Handle more socket events as needed
|
||||
},
|
||||
|
||||
disconnectSocket() {
|
||||
if (this.socket) {
|
||||
this.socket.disconnect();
|
||||
this.socket = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
Reference in New Issue
Block a user