server-state-sync
Version:
State synchronization between multiple clients
54 lines (53 loc) • 1.95 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const uuid_1 = require("uuid");
const State_1 = require("./State");
const Constants_1 = require("../Constants");
class StateManager {
constructor() {
this.states = new Map();
this.addState = (config, identifier) => {
const stateIdentifier = identifier || uuid_1.v4();
if (this.states.has(stateIdentifier)) {
return null;
}
const state = new State_1.default(config, () => this.removeState(stateIdentifier));
this.states.set(stateIdentifier, state);
return stateIdentifier;
};
this.removeState = (identifier) => this.states.delete(identifier);
this.connectToState = (socketClient, stateIdentifier) => {
const state = this.states.get(stateIdentifier);
if (state) {
state.connectClient(socketClient);
}
else {
socketClient.sendMessage({
type: Constants_1.ServerToClientMessageTypes.STATE_CONNECTION_ERROR,
data: {
message: `State with identifier ${stateIdentifier} does not exist`
}
});
}
};
this.removeAllStates = () => {
this.states.forEach((_, key) => {
this.removeState(key);
});
};
}
getStateValue(stateIdentifier) {
const state = this.states.get(stateIdentifier);
if (state) {
return state.getState();
}
}
mutateState(stateIdentifier, updates, clientInformation) {
const state = this.states.get(stateIdentifier);
if (state) {
return state.mutate(updates, clientInformation);
}
return false;
}
}
exports.default = StateManager;
;