UNPKG

@hms-networks/kolibri-js-client

Version:

Kolibri Consumer API client for building kolibri based applications

253 lines 13.2 kB
/* * Copyright 2021 HMS Industrial Networks AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http: //www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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 }; } }; import { isDefined } from '@hms-networks/kolibri-js-core'; import WebSocketAsPromised from 'websocket-as-promised'; import { classToPlain } from 'class-transformer'; import { w3cwebsocket as WebSocket } from 'websocket'; var KolibriConnection = /** @class */ (function () { function KolibriConnection(options) { var _a, _b; this.options = options; this.reconnectRetries = 0; this.reconnectBackoffTime = 1; this.clientMessageListener = options.clientMessageListener; this.reconnectRetries = (_b = (_a = this.options.reconnectOptions) === null || _a === void 0 ? void 0 : _a.maxReconnects) !== null && _b !== void 0 ? _b : 0; } KolibriConnection.prototype.addClientMessageListener = function (listener) { this.clientMessageListener = listener; }; KolibriConnection.prototype.addOnReconnectListener = function (listener) { this.onReconnectListener = listener; }; KolibriConnection.prototype.addOnDisconnectListener = function (listener) { this.onDisconnectListener = listener; }; KolibriConnection.prototype.sendRequest = function (request) { return __awaiter(this, void 0, void 0, function () { var plainRequest, requestId; return __generator(this, function (_a) { plainRequest = classToPlain(request); requestId = request.id; if (!isDefined(this.socket) || !this.socket.isOpened) { throw new Error('Socket is not open!'); } return [2 /*return*/, this.socket.sendRequest(plainRequest, { requestId: requestId })]; }); }); }; KolibriConnection.prototype.sendResponse = function (response) { return __awaiter(this, void 0, void 0, function () { var plainResponse; return __generator(this, function (_a) { plainResponse = classToPlain(response); if (!isDefined(this.socket) || !this.socket.isOpened) { throw new Error('Socket is not open!'); } return [2 /*return*/, this.socket.sendPacked(plainResponse)]; }); }); }; KolibriConnection.prototype.connect = function () { return __awaiter(this, void 0, void 0, function () { var e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: this.socket = this.createWebSocket(this.options.url.toString(), this.options.protocol); this.addListeners(); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.socket.open()]; case 2: _a.sent(); return [3 /*break*/, 4]; case 3: e_1 = _a.sent(); throw new Error('Could not open connection!'); case 4: return [2 /*return*/]; } }); }); }; KolibriConnection.prototype.close = function () { var _a; return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close(); return [2 /*return*/]; }); }); }; KolibriConnection.prototype.disableReconnect = function () { var _a; (_a = this.socket) === null || _a === void 0 ? void 0 : _a.onClose.mute(); }; KolibriConnection.prototype.enableReconnect = function () { var _a; (_a = this.socket) === null || _a === void 0 ? void 0 : _a.onClose.unmute(); }; KolibriConnection.prototype.createWebSocket = function (brokerUrl, kolibriProtocol) { var _this = this; return new WebSocketAsPromised(brokerUrl, { createWebSocket: function (url) { var _a; return new WebSocket(url, kolibriProtocol, undefined, undefined, _this.options.requestOptions, { tlsOptions: (_a = _this.options.tlsOptions) !== null && _a !== void 0 ? _a : {} }); }, packMessage: function (data) { return JSON.stringify(data); }, unpackMessage: function (data) { return JSON.parse(data); }, attachRequestId: function (data, requestId) { return Object.assign({ id: requestId }, data); }, extractRequestId: function (data) { return data && data.id; } }); }; KolibriConnection.prototype.addListeners = function () { var _this = this; var _a, _b, _c, _d; (_a = this.socket) === null || _a === void 0 ? void 0 : _a.onUnpackedMessage.addListener(function (msg) { var _a; (_a = _this.clientMessageListener) === null || _a === void 0 ? void 0 : _a.call(_this, msg); }); if (this.options.reconnectOptions) { (_b = this.socket) === null || _b === void 0 ? void 0 : _b.onClose.addOnceListener(function (event) { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, ((_a = this.onDisconnectListener) === null || _a === void 0 ? void 0 : _a.call(this, { code: event.code, reason: event.reason }))]; case 1: _b.sent(); return [2 /*return*/]; } }); }); }); (_c = this.socket) === null || _c === void 0 ? void 0 : _c.onClose.addListener(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.reconnectHandler()]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }); } else { (_d = this.socket) === null || _d === void 0 ? void 0 : _d.onClose.addListener(function (event) { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, ((_a = this.onDisconnectListener) === null || _a === void 0 ? void 0 : _a.call(this, { code: event.code, reason: event.reason }))]; case 1: _b.sent(); return [2 /*return*/]; } }); }); }); } }; KolibriConnection.prototype.reconnectHandler = function () { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { if (this.reconnectRetries > 0) { setTimeout(function () { return __awaiter(_this, void 0, void 0, function () { var e_2; var _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 3, , 4]); return [4 /*yield*/, ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.open())]; case 1: _c.sent(); // successfully connected this.resetReconnectConfig(); return [4 /*yield*/, ((_b = this.onReconnectListener) === null || _b === void 0 ? void 0 : _b.call(this))]; case 2: _c.sent(); return [3 /*break*/, 4]; case 3: e_2 = _c.sent(); this.prepareReconnectConfigForNextTry(); return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }, this.reconnectBackoffTime * 1000); } else { // Do nothing - Could not reconnect. Giving up } return [2 /*return*/]; }); }); }; KolibriConnection.prototype.resetReconnectConfig = function () { var _this = this; var _a, _b, _c; this.reconnectBackoffTime = 1; this.reconnectRetries = (_b = (_a = this.options.reconnectOptions) === null || _a === void 0 ? void 0 : _a.maxReconnects) !== null && _b !== void 0 ? _b : 0; (_c = this.socket) === null || _c === void 0 ? void 0 : _c.onClose.addOnceListener(function (event) { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, ((_a = this.onDisconnectListener) === null || _a === void 0 ? void 0 : _a.call(this, { code: event.code, reason: event.reason }))]; case 1: _b.sent(); return [2 /*return*/]; } }); }); }); }; KolibriConnection.prototype.prepareReconnectConfigForNextTry = function () { var _a, _b; this.reconnectRetries--; this.reconnectBackoffTime = Math.min(this.reconnectBackoffTime * 2, (_b = (_a = this.options.reconnectOptions) === null || _a === void 0 ? void 0 : _a.maxReconnectDelay) !== null && _b !== void 0 ? _b : 1); }; return KolibriConnection; }()); export { KolibriConnection }; //# sourceMappingURL=kolibri_connection.js.map