UNPKG

@socket.io/postgres-adapter

Version:

The Socket.IO Postgres adapter, allowing to broadcast events between several Socket.IO servers

54 lines (53 loc) 2.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setupPrimary = void 0; const cluster_1 = require("cluster"); const socket_io_adapter_1 = require("socket.io-adapter"); const debug_1 = require("debug"); const util_1 = require("./util"); const debug = (0, debug_1.default)("socket.io-postgres-adapter"); function ignoreError() { } function setupPrimary(pool, opts = {}) { if (!cluster_1.default.isPrimary) { throw "not primary"; } const options = Object.assign({ channelPrefix: "socket.io", tableName: "socket_io_attachments", payloadThreshold: 8000, cleanupInterval: 30000, errorHandler: (err) => debug(err), }, opts); const nodeId = (0, util_1.randomId)(); const client = new util_1.PubSubClient(pool, options, (msg) => { return msg.nodeId === nodeId; }, (msg) => { var _a; debug("forwarding message %s to all workers", msg.type); for (const workerId in cluster_1.default.workers) { (_a = cluster_1.default.workers[workerId]) === null || _a === void 0 ? void 0 : _a.send(msg, ignoreError); } }); cluster_1.default.on("message", async (worker, msg) => { var _a; if (msg.type === socket_io_adapter_1.MessageType.INITIAL_HEARTBEAT) { client.addNamespace(msg.nsp); } const emitterId = String(worker.id); debug("[%s] forwarding message %s to the other workers", nodeId, msg.type); for (const workerId in cluster_1.default.workers) { if (workerId !== emitterId) { (_a = cluster_1.default.workers[workerId]) === null || _a === void 0 ? void 0 : _a.send(msg, ignoreError); } } debug("[%s] forwarding message %s to the other nodes", nodeId, msg.type); msg.nodeId = nodeId; await client.publish(msg); }); return { close() { client.close(); }, }; } exports.setupPrimary = setupPrimary;