jaysonic
Version:
A feature rich JSON-RPC 1.0/2.0 compliant client and server library
166 lines (126 loc) • 7.21 kB
JavaScript
;
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var WebSocket = require("ws");
var JsonRpcClientProtocol = require("./base");
var logging = require("../../util/logger");
/**
* Creates and instance of WsClientProtocol
*
* @extends JsonRpcClientProtocol
* @requires ws
*/
var WsClientProtocol = /*#__PURE__*/function (_JsonRpcClientProtoco) {
_inherits(WsClientProtocol, _JsonRpcClientProtoco);
var _super = _createSuper(WsClientProtocol);
/** @inheritdoc */
/** @property {string} url The websocket URL to connect to, i.e. `ws://127.0.0.1:8100` */
function WsClientProtocol(factory, version, delimiter) {
var _this;
_classCallCheck(this, WsClientProtocol);
_this = _super.call(this, factory, version, delimiter);
_this.url = _this.factory.url;
return _this;
}
/**
* Set the `connector` attribute for the protocol instance. The connector is essentially the
* socket instance for the client.
*
* For the [WsClientProtocol]{@link WsClientProtocol} this is `WebSocket()`
*/
_createClass(WsClientProtocol, [{
key: "setConnector",
value: function setConnector() {
var perMessageDeflate = this.factory.options.perMessageDeflate;
this.connector = new WebSocket(this.url, perMessageDeflate);
this.connector.write = this.connector.send; // tcp uses .write(), ws uses .send()
}
/**
* @inheritdoc
*/
}, {
key: "_retryConnection",
value: function _retryConnection(resolve, reject) {
var _this2 = this;
this.setConnector();
this.connector.onopen = function (event) {
_this2.listener = _this2.connector;
_this2.listen();
resolve(event);
};
this.connector.onerror = function (error) {
// let the onclose event get it otherwise
if (error.error && error.error.code !== "ECONNREFUSED") {
reject(error);
}
};
this.connector.onclose = function (event) {
if (_this2.connector.__clientClosed) {
// we dont want to retry if the client purposefully closed the connection
logging.getLogger().info("Client closed connection. Code [".concat(event.code, "]. Reason [").concat(event.reason, "]."));
} else {
return _this2._onConnectionFailed(event, resolve, reject);
}
};
}
/**
* @inheritdoc
*/
}, {
key: "_onConnectionFailed",
value: function _onConnectionFailed(event, resolve, reject) {
var _this3 = this;
if (this.factory.remainingRetries > 0) {
this.factory.remainingRetries -= 1;
logging.getLogger().error("Failed to connect. Address [".concat(this.url, "]. Retrying. ").concat(this.factory.remainingRetries, " attempts left."));
} else if (this.factory.remainingRetries === 0) {
this.factory.pcolInstance = undefined;
return reject(event);
} else {
logging.getLogger().error("Failed to connect. Address [".concat(this.url, "]. Retrying."));
}
this._connectionTimeout = setTimeout(function () {
_this3._retryConnection(resolve, reject);
}, this.factory.connectionTimeout);
}
/**
* Ends connection to the server.
*
* Sets `JsonRpcClientFactory.pcolInstance` to `undefined`
*
* Clears the connection timeout
*
* @param {number} code Status code for the close event. https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
* @param {string} reason Reason the connection was closed.
*/
}, {
key: "end",
value: function end(code, reason) {
clearTimeout(this._connectionTimeout);
this.factory.pcolInstance = undefined;
this.connector.__clientClosed = true; // used to determine if client initiated close event
this.connector.close(code, reason);
}
/** @inheritdoc */
}, {
key: "listen",
value: function listen() {
var _this4 = this;
this.listener.onmessage = function (message) {
_this4.messageBuffer.push(message.data);
_this4._waitForData(message.data);
};
}
}]);
return WsClientProtocol;
}(JsonRpcClientProtocol);
module.exports = WsClientProtocol;