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-03-02 02:23:12 +00:00
|
|
|
if (!subscriptions || !users) {
|
|
|
|
return;
|
|
|
|
}
|
2022-02-24 01:30:12 +00:00
|
|
|
console.log(`[ConnectionManager] Refreshing connections`);
|
2022-03-02 21:16:30 +00:00
|
|
|
const subscriptionIds = subscriptions.map(s => s.id);
|
2022-02-24 01:30:12 +00:00
|
|
|
const deletedIds = Array.from(this.connections.keys()).filter(id => !subscriptionIds.includes(id));
|
|
|
|
|
|
|
|
// Create and add new connections
|
2022-03-02 21:16:30 +00:00
|
|
|
subscriptions.forEach(subscription => {
|
|
|
|
const id = subscription.id;
|
2022-02-24 01:30:12 +00:00
|
|
|
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-03-02 02:23:12 +00:00
|
|
|
const [user] = users.filter(user => user.baseUrl === baseUrl);
|
2022-02-28 00:29:17 +00:00
|
|
|
const since = subscription.last;
|
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;
|