kuzzle-sdk
Version:
Official Javascript SDK for Kuzzle
85 lines • 3.19 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseProtocolRealtime = void 0;
const Base_1 = require("./Base");
const browser_1 = require("../../utils/browser");
const DisconnectionOrigin_1 = require("../DisconnectionOrigin");
class BaseProtocolRealtime extends Base_1.KuzzleAbstractProtocol {
constructor(host, options = {}, name) {
super(host, options, name);
this.autoReconnect =
typeof options.autoReconnect === "boolean" ? options.autoReconnect : true;
this._reconnectionDelay =
typeof options.reconnectionDelay === "number"
? options.reconnectionDelay
: 1000;
this.wasConnected = false;
this.stopRetryingToConnect = false;
this.retrying = false;
}
/**
* Number of milliseconds between reconnection attempts
*/
get reconnectionDelay() {
return this._reconnectionDelay;
}
connect() {
this.state = "connecting";
return Promise.resolve();
}
/**
* Called when the client's connection is established
*/
clientConnected() {
super.clientConnected("connected", this.wasConnected);
this.state = "connected";
this.wasConnected = true;
this.stopRetryingToConnect = false;
}
/**
* Called when the client's connection is closed
*
* @param {string} origin String that describe what is causing the disconnection
*/
clientDisconnected(origin) {
this.clear();
this.emit("disconnect", { origin });
}
/**
* Called when the client's connection is closed with an error state
*
* @param {KuzzleError} error
*/
clientNetworkError(error) {
// Only emit disconnect once, if the connection was ready before
if (this.isReady()) {
this.emit("disconnect", { origin: DisconnectionOrigin_1.DisconnectionOrigin.NETWORK_ERROR });
}
this.state = "offline";
this.clear();
const connectionError = new Error(`Unable to connect to kuzzle server at ${this.host}:${this.port}: ${error.message} (ws status=${error.status})`);
this.emit("networkError", connectionError);
if (this.autoReconnect && !this.retrying && !this.stopRetryingToConnect) {
this.retrying = true;
const window = (0, browser_1.getBrowserWindow)();
if ((0, browser_1.isBrowser)() &&
typeof window.navigator === "object" &&
window.navigator.onLine === false) {
window.addEventListener("online", () => {
this.retrying = false;
this.connect().catch((err) => this.clientNetworkError(err));
}, { once: true });
return;
}
setTimeout(() => {
this.retrying = false;
this.connect().catch((err) => this.clientNetworkError(err));
}, this.reconnectionDelay);
}
}
isReady() {
return this.state === "connected";
}
}
exports.BaseProtocolRealtime = BaseProtocolRealtime;
//# sourceMappingURL=Realtime.js.map