UNPKG

reshuffle

Version:

Reshuffle is a fast, unopinionated, minimalist integration framework

302 lines 14.1 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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 __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.Reshuffle = void 0; var express_1 = __importDefault(require("express")); var nanoid_1 = require("nanoid"); var availableConnectors = __importStar(require("./connectors")); var persistency_1 = require("./persistency"); var Logger_1 = require("./Logger"); var Reshuffle = /** @class */ (function () { function Reshuffle(loggerOptions) { this.middleware = [express_1["default"].json(), express_1["default"].urlencoded({ extended: true })]; this.availableConnectors = availableConnectors; this.port = parseInt(process.env.PORT, 10) || 8000; this.httpDelegates = {}; this.registry = { connectors: {}, handlers: {}, common: {} }; this.logger = Logger_1.createLogger(loggerOptions); this.logger.info('Reshuffle Initializing'); } Reshuffle.prototype.addMiddleware = function (middleware) { this.middleware.push(middleware); }; Reshuffle.prototype.prepareWebServer = function () { if (!this.registry.common.webserver) { this.registry.common.webserver = express_1["default"](); this.registry.common.webserver.use(this.middleware); } return this.registry.common.webserver; }; Reshuffle.prototype.register = function (connector) { connector.app = this; this.registry.connectors[connector.id] = connector; return this; }; Reshuffle.prototype.unregister = function (connector) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, connector.stop()]; case 1: _a.sent(); delete this.registry.connectors[connector.id]; return [2 /*return*/]; } }); }); }; Reshuffle.prototype.getConnector = function (connectorId) { if (!this.registry.connectors[connectorId]) { this.logger.error("Could not find connector [id=" + connectorId + "]"); } return this.registry.connectors[connectorId]; }; Reshuffle.prototype.registerHTTPDelegate = function (path, delegate) { this.httpDelegates[path] = this.httpDelegates[path] || new HttpMultiplexer(path); this.httpDelegates[path].delegates.push(delegate); return this; }; //we might to add a fine tuned method in the future that just removes one delegete Reshuffle.prototype.unregisterHTTPDelegate = function (path) { var httpMultiplexer = this.httpDelegates[path]; if (httpMultiplexer) { httpMultiplexer.delegates = []; } }; Reshuffle.prototype.when = function (eventConfiguration, handler) { var handlerWrapper = typeof handler === 'object' ? handler : { handle: handler, id: nanoid_1.nanoid() }; if (this.registry.handlers[eventConfiguration.id]) { this.registry.handlers[eventConfiguration.id].push(handlerWrapper); } else { this.registry.handlers[eventConfiguration.id] = [handlerWrapper]; } this.logger.info('Reshuffle Registering event', eventConfiguration.id); return this; }; Reshuffle.prototype.start = function (port, callback) { var _this = this; this.port = port || this.port; // Start all connectors Object.values(this.registry.connectors).forEach(function (connector) { return connector.start(); }); // Start the webserver if we have http delegates if (Object.keys(this.httpDelegates).length) { var webserver_1 = this.prepareWebServer(); if (process.env.RESHUFFLE_HEALTH_PATH) { webserver_1.use(process.env.RESHUFFLE_HEALTH_PATH, function (req, res) { return res.status(200).send({ ok: true, uptime: process.uptime() }); }); } var specificPaths = Object.keys(this.httpDelegates).filter(function (p) { return !p.includes(':'); }); var genericPathsOrdered = Object.keys(this.httpDelegates) .filter(function (p) { return p.includes(':'); }) .sort() .reverse(); // Moves all generic routes (containing :) at the end, with /specific/generic first (e.g. /foo/:id before /:bar) specificPaths.concat(genericPathsOrdered).forEach(function (path) { var httpMultiplexer = _this.httpDelegates[path]; webserver_1.all(path, httpMultiplexer.handle.bind(httpMultiplexer)); }); webserver_1.all('/webhooks/*', function (req, res) { var errorMessage = "Webhook not registered"; _this.logger.info(errorMessage + " for " + req.method + " " + req.url); return res.status(501).send(errorMessage); }); webserver_1.all('*', function (req, res) { var errorMessage = "No handler registered for " + req.method + " " + req.url; _this.logger.info(errorMessage); return res.status(501).send(errorMessage); }); this.httpServer = webserver_1.listen(this.port, function () { _this.logger.info('Reshuffle Web server listening on port', _this.port); }); } callback && callback(); }; Reshuffle.prototype.stopWebServer = function () { var _a; (_a = this.httpServer) === null || _a === void 0 ? void 0 : _a.close(); }; Reshuffle.prototype.restart = function (port) { var _this = this; this.stopWebServer(); this.start(port, function () { _this.logger.info('Reshuffle Restarted'); }); }; Reshuffle.prototype.handleEvent = function (eventId, event) { return __awaiter(this, void 0, void 0, function () { var eventHandlers, handled, _i, eventHandlers_1, handler, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: eventHandlers = this.registry.handlers[eventId]; if (!eventHandlers || eventHandlers.length === 0) { return [2 /*return*/, false]; } handled = true; _i = 0, eventHandlers_1 = eventHandlers; _b.label = 1; case 1: if (!(_i < eventHandlers_1.length)) return [3 /*break*/, 5]; handler = eventHandlers_1[_i]; _a = handled; if (!_a) return [3 /*break*/, 3]; return [4 /*yield*/, this.onHandleEvent(handler, event)]; case 2: _a = (handled = _b.sent()); _b.label = 3; case 3: _a; _b.label = 4; case 4: _i++; return [3 /*break*/, 1]; case 5: return [2 /*return*/, handled]; } }); }); }; Reshuffle.prototype.onHandleEvent = function (handler, event) { return __awaiter(this, void 0, void 0, function () { var error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: this.logger.defaultMeta = { handlerId: handler.id }; _a.label = 1; case 1: _a.trys.push([1, 3, 4, 5]); return [4 /*yield*/, handler.handle(event, this)]; case 2: _a.sent(); return [2 /*return*/, true]; case 3: error_1 = _a.sent(); this.logger.error(error_1.stack); return [2 /*return*/, false]; case 4: this.logger.defaultMeta = {}; return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; Reshuffle.prototype.setPersistentStore = function (adapter) { this.registry.common.persistentStore = adapter; return adapter; }; Reshuffle.prototype.getPersistentStore = function () { return this.registry.common.persistentStore || this.setPersistentStore(new persistency_1.MemoryStoreAdapter()); }; Reshuffle.prototype.getLogger = function () { return this.logger; }; return Reshuffle; }()); exports.Reshuffle = Reshuffle; exports["default"] = Reshuffle; var HttpMultiplexer = /** @class */ (function () { function HttpMultiplexer(originalPath) { this.originalPath = originalPath; this.delegates = []; } HttpMultiplexer.prototype.handle = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var handled, _i, _a, delegate; return __generator(this, function (_b) { switch (_b.label) { case 0: req.originalPath = this.originalPath; handled = false; if (!(this.delegates.length > 0)) return [3 /*break*/, 4]; _i = 0, _a = this.delegates; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; delegate = _a[_i]; if (handled) { return [3 /*break*/, 4]; } return [4 /*yield*/, delegate.handle(req, res, next)]; case 2: handled = _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: if (!handled) { next(); } return [2 /*return*/]; } }); }); }; return HttpMultiplexer; }()); //# sourceMappingURL=Reshuffle.js.map