1 | import http from 'http';
|
2 | import { Server, ServerOptions } from 'socket.io';
|
3 | import { createDebug } from '@feathersjs/commons';
|
4 | import { Application } from '@feathersjs/feathers';
|
5 | import { socket } from '@feathersjs/transport-commons';
|
6 |
|
7 | import { disconnect, params, authentication, FeathersSocket } from './middleware';
|
8 |
|
9 | const debug = createDebug('@feathersjs/socketio');
|
10 |
|
11 | declare module '@feathersjs/feathers/lib/declarations' {
|
12 | interface Application<Services, Settings> {
|
13 | io: Server;
|
14 | listen (options: any): Promise<http.Server>;
|
15 | }
|
16 | }
|
17 |
|
18 | function configureSocketio (callback?: (io: Server) => void): (app: Application) => void;
|
19 | function configureSocketio (options: number | Partial<ServerOptions>, callback?: (io: Server) => void): (app: Application) => void;
|
20 | function configureSocketio (port: number, options?: Partial<ServerOptions>, callback?: (io: Server) => void): (app: Application) => void;
|
21 | function configureSocketio (port?: any, options?: any, config?: any) {
|
22 | if (typeof port !== 'number') {
|
23 | config = options;
|
24 | options = port;
|
25 | port = null;
|
26 | }
|
27 |
|
28 | if (typeof options !== 'object') {
|
29 | config = options;
|
30 | options = {};
|
31 | }
|
32 |
|
33 | return (app: Application) => {
|
34 |
|
35 | const getParams = (socket: FeathersSocket) => socket.feathers;
|
36 |
|
37 | const socketMap = new WeakMap();
|
38 |
|
39 |
|
40 | const done = new Promise(resolve => {
|
41 | const { listen, setup } = app as any;
|
42 |
|
43 | Object.assign(app, {
|
44 | async listen (this: any, ...args: any[]) {
|
45 | if (typeof listen === 'function') {
|
46 |
|
47 |
|
48 | return listen.call(this, ...args);
|
49 | }
|
50 |
|
51 | const server = http.createServer();
|
52 |
|
53 | await this.setup(server);
|
54 |
|
55 | return server.listen(...args);
|
56 | },
|
57 |
|
58 | async setup (this: any, server: http.Server, ...rest: any[]) {
|
59 | if (!this.io) {
|
60 | const io = this.io = new Server(port || server, options);
|
61 |
|
62 | io.use(disconnect(app, getParams));
|
63 | io.use(params(app, socketMap));
|
64 | io.use(authentication(app, getParams));
|
65 |
|
66 |
|
67 |
|
68 |
|
69 | io.sockets.setMaxListeners(64);
|
70 | }
|
71 |
|
72 | if (typeof config === 'function') {
|
73 | debug('Calling SocketIO configuration function');
|
74 | config.call(this, this.io);
|
75 | }
|
76 |
|
77 | resolve(this.io);
|
78 |
|
79 | return setup.call(this, server, ...rest);
|
80 | }
|
81 | });
|
82 | });
|
83 |
|
84 | app.configure(socket({
|
85 | done,
|
86 | socketMap,
|
87 | getParams,
|
88 | emit: 'emit'
|
89 | }));
|
90 | };
|
91 | }
|
92 |
|
93 | export = configureSocketio;
|