@phnq/message
Version:
Asynchronous, incremental messaging client and server
69 lines (68 loc) • 3.23 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketMessageServer = void 0;
const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
const MessageConnection_1 = require("./MessageConnection");
const WebSocketTransport_1 = require("./transports/WebSocketTransport");
class WebSocketMessageServer {
constructor({ httpServer, path = '/' }) {
this.onConnect = () => __awaiter(this, void 0, void 0, function* () { return undefined; });
this.onDisconnect = () => __awaiter(this, void 0, void 0, function* () { return undefined; });
this.onReceive = () => __awaiter(this, void 0, void 0, function* () {
throw new Error('WebSocketMessageServer.onReceive not set');
});
this.connectionsById = new Map();
this.wss = new isomorphic_ws_1.default.Server({ server: httpServer });
this.start(path);
}
getConnection(id) {
return this.connectionsById.get(id);
}
get connections() {
return [...this.connectionsById.values()];
}
close() {
return __awaiter(this, void 0, void 0, function* () {
for (const connection of this.connections) {
yield connection.transport.close();
}
yield new Promise((resolve, reject) => {
try {
this.wss.close(resolve);
}
catch (err) {
reject(err);
}
});
});
}
start(path) {
this.wss.on('connection', (socket, req) => __awaiter(this, void 0, void 0, function* () {
if (req.url !== path) {
socket.close(1008, `unsupported path: ${req.url}`);
return;
}
const connection = new MessageConnection_1.MessageConnection(new WebSocketTransport_1.ServerWebSocketTransport(socket));
this.connectionsById.set(connection.id, connection);
connection.onReceive = (message) => this.onReceive(connection, message);
socket.addListener('close', () => __awaiter(this, void 0, void 0, function* () {
this.connectionsById.delete(connection.id);
yield this.onDisconnect(connection);
}));
yield this.onConnect(connection, req);
}));
}
}
exports.WebSocketMessageServer = WebSocketMessageServer;
;