All files / server/plugins/socket index.js

100% Statements 23/23
100% Branches 8/8
100% Functions 7/7
100% Lines 20/20
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  30x 30x   30x                 11x 36x 29x   16x 16x 16x 1x       140x     140x 140x 140x 7x 8x 8x     7x 7x     7x        
// Create a socket plugin
const socketIO = require('socket.io');
const wildcard = require('socketio-wildcard')();
 
module.exports = {
  name: 'socket',
  options: {
    path: { type: String, env: 'SOCKET_PATH' },
    serveClient: { type: Boolean, env: 'SOCKET_SERVE_CLIENT' },
    adapter: {},
    origins: { type: String, env: 'SOCKET_ORIGINS' },
    parser: {}
  },
  router: (path, ...middle) => async ctx => {
    if (ctx.replied) return;
    if (ctx.path !== path && path !== '*') return;
 
    ctx.replied = true;
    const ret = await ctx.utils.join(middle)(ctx);
    if (ret) {
      ctx.socket.emit(path, ret);
    }
  },
  listen: ctx => {
    const newCtx = ({ socket, path, data }) => Object.assign({}, ctx, {
      method: 'SOCKET', io: ctx.io, path, socket, data
    });
    ctx.io = socketIO(ctx.server, ctx.options.socket);
    ctx.io.use(wildcard);
    ctx.io.on('connect', async socket => {
      socket.on('*', packet => {
        const [path, data] = packet.data;
        ctx.middle(newCtx({ socket, path, data }));
      });
 
      socket.on('disconnect', () => {
        ctx.middle(newCtx({ socket, path: 'disconnect' }));
      });
 
      await ctx.middle(newCtx({ socket, path: 'connect' }));
    });
  }
};