All files / server/plugins/socket index.js

28% Statements 7/25
0% Branches 0/10
14.29% Functions 1/7
33.33% Lines 7/21
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  11x 11x   11x                                         99x     99x 99x 99x                            
// 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.method !== 'SOCKET') 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' }));
    });
  }
};