All files / src/socket index.ts

100% Statements 28/28
100% Branches 0/0
100% Functions 12/12
100% Lines 25/25

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 612x 2x 2x 2x       2x                 2x 6x 6x 6x   6x     6x 6x       6x   36x 3x   3x 3x           6x 6x 6x   36x       12x   12x 2x 2x              
import Debug from 'debug';
import { channels } from '../channels';
import { routing } from '../routing';
import { getDispatcher, runMethod } from './utils';
import { Application } from '@feathersjs/feathers';
import { RealTimeConnection } from '../channels/channel/base';
 
const debug = Debug('@feathersjs/transport-commons');
 
export interface SocketOptions {
  done: Promise<any>;
  emit: string;
  socketKey: any;
  getParams: (socket: any) => RealTimeConnection;
}
 
export function socket({ done, emit, socketKey, getParams }: SocketOptions) {
  return (app: Application) => {
    app.configure(channels());
    app.configure(routing());
 
    app.on('publish', getDispatcher(emit, socketKey));
 
    // `connection` event
    done.then(provider => provider.on('connection', (connection: any) =>
      app.emit('connection', getParams(connection)))
    );
 
    // `socket.emit('methodName', 'serviceName', ...args)` handlers
    done.then(provider => provider.on('connection', (connection: any) => {
      for (const method of app.methods) {
        connection.on(method, (...args: any[]) => {
          const path = args.shift();
 
          debug(`Got '${method}' call for service '${path}'`);
          runMethod(app, getParams(connection), path, method, args);
        });
      }
    }));
 
    // Legacy `socket.emit('serviceName::methodName', ...args)` handlers
    app.mixins.push((service, path) => done.then(provider => {
      provider.on('connection', (socket: any) => {
        const methods = app.methods.filter(current =>
          // @ts-ignore
          typeof service[current] === 'function'
        );
 
        for (const method of methods) {
          const eventName = `${path}::${method}`;
 
          socket.on(eventName, (...args: any[]) => {
            debug(`Got legacy method call '${eventName}'`);
            runMethod(app, getParams(socket), path, method, args);
          });
        }
      });
    }));
  };
}