Skip to content

Commit

Permalink
refactor(ConnectionHub): fix missing connection id issue (#3180)
Browse files Browse the repository at this point in the history
  • Loading branch information
ArgoZhang authored Mar 30, 2024
1 parent 8da7201 commit 56e2c7a
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions src/BootstrapBlazor/wwwroot/modules/hub.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,46 @@ import EventHandler from "./event-handler.js?v=$version";

export async function init(id, options) {
const { invoke, method, interval = 3000, url, connectionId } = options;
const hubs = [];
const chanel = new BroadcastChannel('bb_hubs_chanel');
const localStorageKey = 'bb_hub_el_id';
const localStorageConnectionIdKey = 'bb_hub_connection_id';
if (localStorage.getItem(localStorageKey) === null) {
localStorage.setItem(localStorageKey, id);
}

const localStorageConnectionIdKey = 'bb_hub_connection_id';
let clientId = localStorage.getItem(localStorageConnectionIdKey);
if (clientId === null) {
localStorage.setItem(localStorageConnectionIdKey, connectionId);
clientId = connectionId;
}
window.addEventListener('unload', () => {
chanel.close();
localStorage.removeItem(localStorageKey);
dispose(id);
});

const hubs = [];
const chanel = new BroadcastChannel('bb_hubs_chanel');
EventHandler.on(chanel, 'message', e => {
const id = e.data;
if (hubs.find(v => v === id) === void 0) {
const { id, type } = e.data;
if (type === 'ping' && hubs.find(v => v === id) === void 0) {
hubs.push(id);
}
else if (type === 'dispose') {
const index = hubs.indexOf(v => v === id);
if (index > -1) {
hubs.splice(index, 1);
}
if (clientId === connectionId) {
localStorage.removeItem(localStorageConnectionIdKey);
}
if (localStorage.getItem(localStorageKey) === id) {
localStorage.removeItem(localStorageKey);
}
}
});

const info = await getClientInfo(url);
info.id = clientId;
const handler = setInterval(async () => {
chanel.postMessage(id);
chanel.postMessage({ id, type: 'ping' });
let hubId = localStorage.getItem(localStorageKey);

if (hubId === null) {
Expand All @@ -48,18 +59,21 @@ export async function init(id, options) {
localStorage.removeItem(localStorageKey);
}
}
else {
localStorage.removeItem(localStorageKey);
}
}, interval);

const hub = { handler, chanel };
const hub = { handler, chanel, connectionId };
Data.set(id, hub);
}

export async function dispose(id) {
const hub = Data.get(id);

if (hub) {
hub.chanel.close();
clearInterval(hub.handler);
localStorage.removeItem('bootstrapblazor_hub_id');
hub.chanel.postMessage({ id, type: 'dispose' });
hub.chanel.close();
}
}

0 comments on commit 56e2c7a

Please sign in to comment.