You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cvm/lib/websockets/tracker.js

72 lines
1.7 KiB
JavaScript

'use strict';
const websocketDeduplicator = require("./deduplicator");
const findAndSplice = require("../find-and-splice");
module.exports = function(options) {
let deduplicator, externalDeduplicatorProvided;
if (options.deduplicator != null) {
deduplicator = options.deduplicator;
externalDeduplicatorProvided = true;
} else {
deduplicator = websocketDeduplicator();
externalDeduplicatorProvided = false;
}
if (options.namespaced) {
let clients = {};
return {
add: function addClient(namespace, client) {
if (clients[namespace] == null) {
clients[namespace] = [];
}
clients[namespace].push(client);
},
remove: function removeClient(client) {
Object.keys(clients).forEach((namespace) => {
this.removeFromNamespace(namespace, client);
});
if (externalDeduplicatorProvided === false) {
deduplicator.forgetClient(client);
}
},
removeFromNamespace: function removeClientFromNamespace(namespace, client) {
findAndSplice(clients[namespace], client);
},
emit: function emit(namespace, data) {
let namespacedClients = clients[namespace];
if (namespacedClients != null) {
namespacedClients.forEach((client) => {
deduplicator(client, data, () => {
client.send(JSON.stringify(data));
});
});
}
}
}
} else {
let clients = [];
return {
add: function addClient(client) {
clients.push(client);
},
remove: function removeClient(client) {
findAndSplice(clients, client);
},
emit: function emit(data) {
clients.forEach((client) => {
deduplicator(client, data, () => {
client.send(JSON.stringify(data));
});
});
}
}
}
}