sticky-horse
Version:
With StickyHorse allow your users to send feedback to your team.
67 lines (66 loc) • 2.57 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.disconnectSocket = exports.getSocket = exports.initializeSocket = void 0;
var socket_io_client_1 = require("socket.io-client");
var getUserId_1 = require("./getUserId");
// import { getStickyHorseConfig } from '..';
var globalSocket = null;
var initializeSocket = function (userId, params, apiKey) {
if (!userId) {
console.error('userId is required for socket initialization');
return null;
}
// Don't create new socket if one exists and is connected
if (globalSocket === null || globalSocket === void 0 ? void 0 : globalSocket.connected) {
return globalSocket;
}
var socketUrl = 'https://sticky-horse.onrender.com'; //process.env.URL_Server // 'http://localhost:4000'; // 'https://sticky-horse.onrender.com'; // http://localhost:4000 configuration.socketUrl ||
var socket = (0, socket_io_client_1.io)(socketUrl, {
query: {
userId: userId,
isTracking: (params === null || params === void 0 ? void 0 : params.isTracking) || false,
targetId: (params === null || params === void 0 ? void 0 : params.targetId) || '',
page: (params === null || params === void 0 ? void 0 : params.page) || window.location.pathname,
apiKey: apiKey
},
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000
});
socket.on('connect', function () {
console.log('Socket connected with userId:', userId);
globalSocket = socket;
});
socket.on('connect_error', function (error) {
console.error('Socket connection error:', error);
});
return socket;
};
exports.initializeSocket = initializeSocket;
var getSocket = function () {
// If no global socket exists, try to initialize it
if (!globalSocket) {
// const config = getStickyHorseConfig();
var userId = (0, getUserId_1.getUserId)();
try {
var socket = (0, exports.initializeSocket)(userId);
if (socket) {
globalSocket = socket;
return socket;
}
}
catch (error) {
console.error('Failed to initialize socket:', error);
}
}
return globalSocket;
};
exports.getSocket = getSocket;
var disconnectSocket = function () {
if (globalSocket) {
globalSocket.disconnect();
globalSocket = null;
}
};
exports.disconnectSocket = disconnectSocket;
;