UNPKG

2.51 kBJavaScriptView Raw
1const socketio = require('socket.io');
2const Proto = require('uberproto');
3const http = require('http');
4const { socket: commons } = require('@feathersjs/transport-commons');
5const debug = require('debug')('@feathersjs/socketio');
6
7const middleware = require('./middleware');
8
9function 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 // Function that gets the connection
23 const getParams = socket => socket.feathers;
24 // A mapping from connection to socket instance
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 // Promise that resolves with the Socket.io `io` instance
32 // when `setup` has been called (with a server)
33 const done = new Promise(resolve => {
34 Proto.mixin({
35 listen (...args) {
36 if (typeof this._super === 'function') {
37 // If `listen` already exists
38 // usually the case when the app has been expressified
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 // In Feathers it is easy to hit the standard Node warning limit
58 // of event listeners (e.g. by registering 10 services).
59 // So we set it to a higher number. 64 should be enough for everyone.
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
84module.exports = configureSocketio;
85module.exports.default = configureSocketio;