UNPKG

2.12 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * Simpler interface over a collection of sockets. Works with
5 * WebSocket clients, or sockets from a WebSocket server.
6 * @class
7 */
8function Pool () {
9 if (!(this instanceof Pool)) {
10 return new Pool();
11 }
12
13 // Maps IDs to sockets.
14 this.sockets = {};
15}
16
17var API = Pool.prototype;
18
19/**
20 * Returns the socket by the given ID.
21 * @param {String} id - The unique socket ID.
22 * @return {WebSocket|Null} - The WebSocket, if found.
23 */
24API.get = function (id) {
25 return this.sockets[id] || null;
26};
27
28/**
29 * Adds a socket to the pool.
30 * @param {String} id - The socket ID.
31 * @param {WebSocket} socket - A websocket instance.
32 * @return {Pool} - The context.
33 */
34API.add = function (id, socket) {
35 this.sockets[id] = socket;
36
37 return this;
38};
39
40/**
41 * Removes a socket from the pool.
42 * @param {String} id - The ID of the socket to remove.
43 * @return {Boolean} - Whether the pool contained the socket.
44 */
45API.remove = function (id) {
46 var sockets = this.sockets;
47 var hasSocket = sockets.hasOwnProperty(id);
48
49 if (hasSocket) {
50 delete sockets[id];
51 }
52
53 return hasSocket;
54};
55
56/**
57 * Creates a filtered pool of sockets. Works the same as Array#filter.
58 * @param {Function} fn - Called for each socket in the pool.
59 * @param {Mixed} [_this] - The `this` context to use when invoking
60 * the callback.
61 * @return {Pool} - A new, filtered socket pool.
62 */
63API.filter = function (fn, _this) {
64 var filtered = Pool();
65 var pool = this;
66
67 _this = _this || pool;
68
69 Object.keys(this.sockets).forEach(function (id) {
70 var socket = pool.sockets[id];
71
72 var shouldAdd = fn.call(_this, socket, id, pool);
73
74 // Add it to the new pool.
75 if (shouldAdd) {
76 filtered.add(id, socket);
77 }
78 });
79
80 return filtered;
81};
82
83/**
84 * Send a message through each socket in the pool.
85 * @param {String} msg - The message to send.
86 * @return {Number} - How many sockets the message was sent to.
87 */
88API.send = function (msg) {
89 var pool = this;
90
91 var ids = Object.keys(this.sockets);
92
93 ids.forEach(function (id) {
94 var socket = pool.sockets[id];
95 socket.send(msg);
96 });
97
98 return ids.length;
99};
100
101module.exports = Pool;