All files / src/channels/channel combined.ts

100% Statements 22/22
100% Branches 1/1
100% Functions 10/10
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 582x     19x 19x   19x 33x   24x 24x         19x     2x         15x   15x   15x 15x       4x   4x       2x       2x       3x         8x 4x   4x      
import { Channel, RealTimeConnection } from './base';
 
function collectConnections (children: Channel[]) {
  const mappings = new WeakMap<RealTimeConnection, any>();
  const connections: RealTimeConnection[] = [];
 
  children.forEach(channel => {
    channel.connections.forEach(connection => {
      if (!mappings.has(connection)) {
        connections.push(connection);
        mappings.set(connection, channel.data);
      }
    });
  });
 
  return { connections, mappings };
}
 
export class CombinedChannel extends Channel {
  children: Channel[];
  mappings: WeakMap<RealTimeConnection, any>;
 
  constructor (children: Channel[], data: any = null) {
    const { mappings, connections } = collectConnections(children);
 
    super(connections, data);
 
    this.children = children;
    this.mappings = mappings;
  }
 
  refresh () {
    const collected = collectConnections(this.children);
 
    return Object.assign(this, collected);
  }
 
  leave (...connections: RealTimeConnection[]) {
    return this.callChildren('leave', connections);
  }
 
  join (...connections: RealTimeConnection[]) {
    return this.callChildren('join', connections);
  }
 
  dataFor (connection: RealTimeConnection) {
    return this.mappings.get(connection);
  }
 
  private callChildren (method: string, connections: RealTimeConnection[]) {
    // @ts-ignore
    this.children.forEach(child => child[method](...connections));
    this.refresh();
 
    return this;
  }
}