# All files / server/plugins/socket index.js

31.81% Statements 7/22
20% Branches 2/10
14.28% Functions 1/7
36.84% Lines 7/19

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
    58
    59
    60
    61
    62
    63
    64
    27x

    27x

    27x

    102x
    102x

    102x
    102x

     // Create a socket plugin
    const socketIO = require('socket.io');

    const listeners = {};

    module.exports = {
      name: 'socket',
      options: {
        path: {
          env: 'SOCKET_PATH'
        },
        serveClient: {},
        adapter: {},
        origins: {},
        parser: {},
        pingTimeout: {},
        pingInterval: {},
        upgradeTimeout: {},
        maxHttpBufferSize: {},
        allowRequest: {},
        transports: {},
        allowUpgrades: {},
        perMessageDeflate: {},
        httpCompression: {},
        cookie: {},
        cookiePath: {},
        cookieHttpOnly: {},
        wsEngine: {}
      },
      router: (path, middle) => {
        listeners[path] = listeners[path] || [];
        listeners[path].push(middle);
      },
      launch: ctx => {
        Iif (!ctx.options.socket) return;
        Iif (listeners.ping) {
          ctx.log.warning('socket("ping") has a special meaning, please avoid it');
        }
        ctx.io = socketIO(ctx.server, ctx.options.socket);
        ctx.io.on('connect', socket => {
          // Create a new context assigned to each connected socket
          const createContext = extra => {
            return Object.assign({}, socket.client.request, ctx, extra);
          };

          // Attach a `socket.on('name', cb)` to each of the callbacks
          for (let path in listeners) {
            if (path !== 'connect') {
              listeners[path].forEach(cb => {
                socket.on(path, data => cb(createContext({ path, socket, data })));
              });
            }
          }

          // This is not a callback and should be called straight away since we are
          // already inside `io.on('connect')`
          const path = 'connect';
          if (listeners['connect']) {
            listeners[path].forEach(cb => cb(createContext({ path, socket })));
          }
        });
      }
    };