server-state-sync
Version:
State synchronization between multiple clients
73 lines (72 loc) • 3.42 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Ws = require("ws");
const Https = require("https");
const Http = require("http");
const url_1 = require("url");
const SocketClient_1 = require("./SocketClient");
const StateManager_1 = require("./StateManager");
class StateSyncer {
constructor(ssl) {
this.onUpgrade = (request, socket, head) => {
this._authenticateClient(request, (clientInformation, success) => {
if (!success) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
this.webSocketServer.handleUpgrade(request, socket, head, (ws) => {
if (request.url) {
const clientIdentifier = url_1.parse(request.url, true).query.identifier;
if (clientIdentifier) {
this.webSocketServer.emit('connection', ws, clientInformation, clientIdentifier);
}
else {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
}
});
});
};
this.onConnection = (socket, clientInformation, identifier) => {
new SocketClient_1.default(socket, this, clientInformation, identifier);
};
this._authenticateClient = (_, callback) => {
callback(null, true);
};
this.useAuthorizationMiddleware = (middleWare) => {
this._authenticateClient = middleWare;
};
/*
Returns null if there is a state with the same identifier, else returns the identifier
*/
this.createState = (config, identifier) => this.stateManager.addState(config, identifier);
/*
Returns true if state was deleted, false if it did not exist
*/
this.removeState = (stateIdentifier) => this.stateManager.removeState(stateIdentifier);
this.removeAllStates = () => this.stateManager.removeAllStates();
this.connectToState = (socketClient, stateIdentifier) => this.stateManager.connectToState(socketClient, stateIdentifier);
this.getValueOfState = (stateIdentifier) => this.stateManager.getStateValue(stateIdentifier);
this.updateStateValue = (stateIdentifier, updates, clientInformation) => this.stateManager.mutateState(stateIdentifier, updates, clientInformation);
this.start = (port) => {
return new Promise((resolve, reject) => {
this.externalServer.on('error', reject);
this.externalServer.listen(port, undefined, undefined, resolve);
});
};
this.stateManager = new StateManager_1.default();
this.webSocketServer = new Ws.Server({ noServer: true });
this.webSocketServer.on('connection', this.onConnection);
if (ssl) {
this.externalServer = Https.createServer({ cert: ssl.cert, key: ssl.key });
}
else {
this.externalServer = Http.createServer();
}
this.externalServer.on('upgrade', this.onUpgrade);
}
}
exports.default = StateSyncer;