UNPKG

server-state-sync

Version:
86 lines (85 loc) 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Constants_1 = require("../Constants"); class SocketClient { constructor(socket, stateSyncer, clientInformation, identifier) { this.setUpEventListeners = (socket) => { socket.onopen = () => { }; socket.onclose = () => { }; socket.onerror = () => { }; socket.onmessage = this.onMessage; }; this.onMessage = (event) => { try { const { data, type } = JSON.parse(event.data); switch (type) { case Constants_1.ClientToServerMessageTypes.UPDATE_STATE: this.onStateUpdateRequest(data); break; case Constants_1.ClientToServerMessageTypes.CONNECT_TO_STATE: this.onConnectToStateRequest(data); break; default: this.sendMessage({ type: Constants_1.ServerToClientMessageTypes.UNSUPPORTED_MESSAGE_TYPE, data: { message: `Message type ${type} is not supported` } }); break; } } catch (e) { console.error(e); } }; this.onConnectToStateRequest = ({ stateIdentifier }) => { if (stateIdentifier) { if (this.state) { this.state.disconnectClient(this); } this.stateSyncer.connectToState(this, stateIdentifier); } else { this.sendMessage({ type: Constants_1.ServerToClientMessageTypes.STATE_CONNECTION_ERROR, data: { message: 'Could not connect to state, no stateIdentifier was supplied' } }); } }; this.onStateUpdateRequest = ({ updates }) => { if (this.state && updates) { this.state.mutate(updates, this.clientInformation); } else { this.sendMessage({ type: Constants_1.ServerToClientMessageTypes.STATE_UPDATE_FAILED, data: { message: 'Could not update state' } }); } }; this.onStateConnected = (state) => { this.state = state; this.socket.onclose = () => state.disconnectClient(this); this.sendMessage({ type: Constants_1.ServerToClientMessageTypes.STATE_CONNECTION_ESTABLISHED, data: { state: state.getState() } }); }; this.sendMessage = (msg) => { this.socket.send(JSON.stringify(msg)); }; this.socket = socket; this.stateSyncer = stateSyncer; this.clientInformation = clientInformation; this.identifier = identifier; this.setUpEventListeners(socket); } } exports.default = SocketClient;