1 | const socketio = require('socket.io');
|
2 | const Proto = require('uberproto');
|
3 | const http = require('http');
|
4 | const { socket: commons } = require('@feathersjs/transport-commons');
|
5 | const debug = require('debug')('@feathersjs/socketio');
|
6 |
|
7 | const middleware = require('./middleware');
|
8 |
|
9 | function configureSocketio (port, options, config) {
|
10 | if (typeof port !== 'number') {
|
11 | config = options;
|
12 | options = port;
|
13 | port = null;
|
14 | }
|
15 |
|
16 | if (typeof options !== 'object') {
|
17 | config = options;
|
18 | options = {};
|
19 | }
|
20 |
|
21 | return function (app) {
|
22 |
|
23 | const getParams = socket => socket.feathers;
|
24 |
|
25 | const socketMap = new WeakMap();
|
26 |
|
27 | if (!app.version || app.version < '3.0.0') {
|
28 | throw new Error('@feathersjs/socketio is not compatible with this version of Feathers. Use the latest at @feathersjs/feathers.');
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 | const done = new Promise(resolve => {
|
34 | Proto.mixin({
|
35 | listen (...args) {
|
36 | if (typeof this._super === 'function') {
|
37 |
|
38 |
|
39 | return this._super(...args);
|
40 | }
|
41 |
|
42 | const server = http.createServer();
|
43 |
|
44 | this.setup(server);
|
45 |
|
46 | return server.listen(...args);
|
47 | },
|
48 |
|
49 | setup (server) {
|
50 | if (!this.io) {
|
51 | const io = this.io = socketio.listen(port || server, options);
|
52 |
|
53 | io.use(middleware.disconnect(app, getParams));
|
54 | io.use(middleware.params(app, socketMap));
|
55 | io.use(middleware.authentication(app, getParams));
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | io.sockets.setMaxListeners(64);
|
61 | }
|
62 |
|
63 | if (typeof config === 'function') {
|
64 | debug('Calling SocketIO configuration function');
|
65 | config.call(this, this.io);
|
66 | }
|
67 |
|
68 | resolve(this.io);
|
69 |
|
70 | return this._super.apply(this, arguments);
|
71 | }
|
72 | }, app);
|
73 | });
|
74 |
|
75 | app.configure(commons({
|
76 | done,
|
77 | socketMap,
|
78 | getParams,
|
79 | emit: 'emit'
|
80 | }));
|
81 | };
|
82 | }
|
83 |
|
84 | module.exports = configureSocketio;
|
85 | module.exports.default = configureSocketio;
|