2022-02-24 01:30:12 +00:00
|
|
|
import Connection from "./Connection";
|
|
|
|
|
2022-02-26 04:25:04 +00:00
|
|
|
class ConnectionManager {
|
2022-02-24 01:30:12 +00:00
|
|
|
constructor() {
|
|
|
|
this.connections = new Map();
|
|
|
|
}
|
|
|
|
|
2022-02-26 04:25:04 +00:00
|
|
|
refresh(subscriptions, users, onNotification) {
|
2022-02-24 01:30:12 +00:00
|
|
|
console.log(`[ConnectionManager] Refreshing connections`);
|
|
|
|
const subscriptionIds = subscriptions.ids();
|
|
|
|
const deletedIds = Array.from(this.connections.keys()).filter(id => !subscriptionIds.includes(id));
|
|
|
|
|
|
|
|
// Create and add new connections
|
|
|
|
subscriptions.forEach((id, subscription) => {
|
|
|
|
const added = !this.connections.get(id)
|
|
|
|
if (added) {
|
2022-02-24 14:52:49 +00:00
|
|
|
const baseUrl = subscription.baseUrl;
|
|
|
|
const topic = subscription.topic;
|
2022-02-26 04:25:04 +00:00
|
|
|
const user = users.get(baseUrl);
|
2022-02-24 14:52:49 +00:00
|
|
|
const since = 0;
|
2022-02-26 04:25:04 +00:00
|
|
|
const connection = new Connection(id, baseUrl, topic, user, since, onNotification);
|
2022-02-24 01:30:12 +00:00
|
|
|
this.connections.set(id, connection);
|
2022-02-24 14:52:49 +00:00
|
|
|
console.log(`[ConnectionManager] Starting new connection ${id}`);
|
2022-02-24 01:30:12 +00:00
|
|
|
connection.start();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Delete old connections
|
|
|
|
deletedIds.forEach(id => {
|
|
|
|
console.log(`[ConnectionManager] Closing connection ${id}`);
|
|
|
|
const connection = this.connections.get(id);
|
|
|
|
this.connections.delete(id);
|
2022-02-24 14:52:49 +00:00
|
|
|
connection.close();
|
2022-02-24 01:30:12 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const connectionManager = new ConnectionManager();
|
|
|
|
export default connectionManager;
|