Correctly handle socket state in the app and make it possible to listen for events
This commit is contained in:
parent
f0ca8bc3a3
commit
c8d89e0964
6 changed files with 89 additions and 16 deletions
|
@ -2,16 +2,21 @@ import getServer, { Server } from '@/api/server/getServer';
|
|||
import { action, Action, thunk, Thunk } from 'easy-peasy';
|
||||
import socket, { SocketState } from './socket';
|
||||
|
||||
export type ServerStatus = 'offline' | 'starting' | 'stopping' | 'online';
|
||||
|
||||
export interface ServerState {
|
||||
data?: Server;
|
||||
status: ServerStatus;
|
||||
socket: SocketState;
|
||||
getServer: Thunk<ServerState, string, {}, any, Promise<void>>;
|
||||
setServer: Action<ServerState, Server>;
|
||||
setServerStatus: Action<ServerState, ServerStatus>;
|
||||
clearServerState: Action<ServerState>;
|
||||
}
|
||||
|
||||
const server: ServerState = {
|
||||
socket,
|
||||
status: 'offline',
|
||||
getServer: thunk(async (actions, payload) => {
|
||||
const server = await getServer(payload);
|
||||
actions.setServer(server);
|
||||
|
@ -19,10 +24,14 @@ const server: ServerState = {
|
|||
setServer: action((state, payload) => {
|
||||
state.data = payload;
|
||||
}),
|
||||
setServerStatus: action((state, payload) => {
|
||||
state.status = payload;
|
||||
}),
|
||||
clearServerState: action(state => {
|
||||
state.data = undefined;
|
||||
|
||||
if (state.socket.instance) {
|
||||
state.socket.instance.removeAllListeners();
|
||||
state.socket.instance.close();
|
||||
}
|
||||
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
import { Action, action } from 'easy-peasy';
|
||||
import Sockette from 'sockette';
|
||||
import { Websocket } from '@/plugins/Websocket';
|
||||
|
||||
export interface SocketState {
|
||||
instance: Sockette | null;
|
||||
instance: Websocket | null;
|
||||
connected: boolean;
|
||||
setInstance: Action<SocketState, Sockette | null>;
|
||||
setInstance: Action<SocketState, Websocket | null>;
|
||||
setConnectionState: Action<SocketState, boolean>;
|
||||
}
|
||||
|
||||
|
|
Reference in a new issue