UNPKG

@steelbreeze/broker

Version:

Lightweight publish and subscribe using Server-Sent Events for node and express

61 lines (60 loc) 2.89 kB
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); var http = __importStar(require("http")); var EventSource = require('eventsource'); /** * Returns the client API to the message broker, providing publish and subscribe operations. * @param config Configuration specifying the server, port and base URL path of the message broker server. * @returns Returns a client providing publish and subscribe operations. */ function client(config) { return { /** * Publishes a message to a message broker for other client to receive based on their subscriptions. * @param topicName The topic to publish on. This may be one or more URL segments. * @param data The data to publish on the topic * @param onError Optional error handler callback */ publish: function (topicName, data, onError) { if (onError === void 0) { onError = undefined; } var post = http.request({ hostname: config.host, port: config.port, path: config.path + "/" + topicName, method: 'POST', headers: { 'Content-Type': 'text/plain', 'Content-Length': Buffer.byteLength(data) } }); // trap and propigate error messages as required post.on('error', function (err) { if (onError) { onError(err); } }); // send message to the server post.write(data); post.end(); }, /** * Registers a subscription to messages on the given topic. The callback is called each time a message to published on the same topic. * @param topicName The topic to subscribe to. This may be one or more URL segments. * @param callback The function to call when data is publised on the topic; passing a message object. */ subscribe: function (topicName, callback) { var eventSource = new EventSource("http://" + config.host + ":" + config.port + config.path + "/" + topicName); var lastEventId = -1; // process messages from the server eventSource.onmessage = function (event) { // perform a duplicate message check if (event.lastEventId !== lastEventId) { lastEventId = event.lastEventId; // propigate message to the client if (callback) { callback({ topicName: topicName, id: event.lastEventId, data: event.data }); } } }; } }; } exports.client = client;