server-state-sync
Version:
State synchronization between multiple clients
61 lines (60 loc) • 2.59 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Constants_1 = require("../Constants");
class State {
constructor(config, destructionHandler) {
this.connectedClients = [];
this.connectClient = (socketClient) => {
if (this.allowConnectingClient(socketClient.clientInformation)) {
this.connectedClients.push(socketClient);
socketClient.onStateConnected(this);
}
else {
socketClient.sendMessage({
type: Constants_1.ServerToClientMessageTypes.STATE_CONNECTION_ERROR,
data: {
message: 'Not allowed to connect to this state'
}
});
}
};
this.disconnectClient = (socketClient) => {
this.connectedClients = this.connectedClients.filter(connectedClient => connectedClient.identifier !== socketClient.identifier);
if (this.selfDestruct(this.connectedClients.length, this.timeOfCreation)) {
this.destroy();
}
};
this.mutate = (updates, clientInformation) => {
const afterInterception = this.interceptStateUpdate(updates, clientInformation);
if (afterInterception == null) {
return false;
}
this.value = Object.assign(Object.assign({}, this.value), afterInterception);
this.broadcastStateUpdate(afterInterception);
return true;
};
this.broadcastStateUpdate = (updates) => {
this.connectedClients.forEach(socketClient => {
socketClient.sendMessage({
type: Constants_1.ServerToClientMessageTypes.STATE_UPDATED,
data: {
updates
}
});
});
};
this.destroy = () => {
this.destructionHandler();
};
this.timeOfCreation = new Date();
this.value = config.initialValue;
this.interceptStateUpdate = config.interceptStateUpdate ? config.interceptStateUpdate : (updates) => updates;
this.allowConnectingClient = config.allowConnectingClient ? config.allowConnectingClient : () => true;
this.selfDestruct = config.selfDestruct ? config.selfDestruct : () => false;
this.destructionHandler = destructionHandler;
}
getState() {
return this.value;
}
}
exports.default = State;