2022-02-24 02:30:12 +01:00
|
|
|
import Connection from "./Connection";
|
|
|
|
|
2022-02-26 05:25:04 +01:00
|
|
|
class ConnectionManager {
|
2022-02-24 02:30:12 +01:00
|
|
|
constructor() {
|
|
|
|
this.connections = new Map();
|
|
|
|
}
|
|
|
|
|
2022-02-26 05:25:04 +01:00
|
|
|
refresh(subscriptions, users, onNotification) {
|
2022-03-02 03:23:12 +01:00
|
|
|
if (!subscriptions || !users) {
|
|
|
|
return;
|
|
|
|
}
|
2022-02-24 02:30:12 +01: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 15:52:49 +01:00
|
|
|
const baseUrl = subscription.baseUrl;
|
|
|
|
const topic = subscription.topic;
|
2022-03-02 03:23:12 +01:00
|
|
|
const [user] = users.filter(user => user.baseUrl === baseUrl);
|
2022-02-28 01:29:17 +01:00
|
|
|
const since = subscription.last;
|
2022-02-26 05:25:04 +01:00
|
|
|
const connection = new Connection(id, baseUrl, topic, user, since, onNotification);
|
2022-02-24 02:30:12 +01:00
|
|
|
this.connections.set(id, connection);
|
2022-02-24 15:52:49 +01:00
|
|
|
console.log(`[ConnectionManager] Starting new connection ${id}`);
|
2022-02-24 02:30:12 +01: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 15:52:49 +01:00
|
|
|
connection.close();
|
2022-02-24 02:30:12 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const connectionManager = new ConnectionManager();
|
|
|
|
export default connectionManager;
|