mirror of https://github.com/ghostfolio/ghostfolio
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
2.0 KiB
60 lines
2.0 KiB
/**
|
|
* The following code is modified based on
|
|
* https://github.com/webpack/webpack-dev-server
|
|
*
|
|
* MIT Licensed
|
|
* Author Tobias Koppers @sokra
|
|
* Copyright (c) JS Foundation and other contributors
|
|
* https://github.com/webpack/webpack-dev-server/blob/main/LICENSE
|
|
*/
|
|
import WebSocketClient from './clients/WebSocketClient.js';
|
|
import { log } from './utils/log.js';
|
|
// this WebsocketClient is here as a default fallback, in case the client is not injected
|
|
var Client = typeof __webpack_dev_server_client__ !== 'undefined'
|
|
? typeof __webpack_dev_server_client__.default !== 'undefined'
|
|
? __webpack_dev_server_client__.default
|
|
: __webpack_dev_server_client__
|
|
: WebSocketClient;
|
|
var retries = 0;
|
|
var maxRetries = 10;
|
|
// Initialized client is exported so external consumers can utilize the same instance
|
|
// It is mutable to enforce singleton
|
|
export var client = null;
|
|
var timeout;
|
|
function socket(url, handlers, reconnect) {
|
|
client = new Client(url);
|
|
client.onOpen(function () {
|
|
retries = 0;
|
|
if (timeout) {
|
|
clearTimeout(timeout);
|
|
}
|
|
if (typeof reconnect !== 'undefined') {
|
|
maxRetries = reconnect;
|
|
}
|
|
});
|
|
client.onClose(function () {
|
|
if (retries === 0) {
|
|
handlers.close();
|
|
}
|
|
// Try to reconnect.
|
|
client = null;
|
|
// After 10 retries stop trying, to prevent logspam.
|
|
if (retries < maxRetries) {
|
|
// Exponentially increase timeout to reconnect.
|
|
// Respectfully copied from the package `got`.
|
|
var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
|
|
retries += 1;
|
|
log.info('Trying to reconnect...');
|
|
timeout = setTimeout(function () {
|
|
socket(url, handlers, reconnect);
|
|
}, retryInMs);
|
|
}
|
|
});
|
|
client.onMessage(function (data) {
|
|
var message = JSON.parse(data);
|
|
if (handlers[message.type]) {
|
|
handlers[message.type](message.data, message.params);
|
|
}
|
|
});
|
|
}
|
|
export default socket;
|
|
|