-
-
Notifications
You must be signed in to change notification settings - Fork 173
/
index.js
63 lines (59 loc) · 1.64 KB
/
index.js
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
61
62
63
// Create a socket plugin
const socketIO = require('socket.io');
const listeners = {};
module.exports = {
name: 'socket',
options: {
path: {
env: 'SOCKET_PATH'
},
serveClient: {},
adapter: {},
origins: {},
parser: {},
pingTimeout: {},
pingInterval: {},
upgradeTimeout: {},
maxHttpBufferSize: {},
allowRequest: {},
transports: {},
allowUpgrades: {},
perMessageDeflate: {},
httpCompression: {},
cookie: {},
cookiePath: {},
cookieHttpOnly: {},
wsEngine: {}
},
router: (path, middle) => {
listeners[path] = listeners[path] || [];
listeners[path].push(middle);
},
launch: ctx => {
if (!ctx.options.socket) return;
if (listeners.ping) {
ctx.log.warning('socket("ping") has a special meaning, please avoid it');
}
ctx.io = socketIO(ctx.server, ctx.options.socket);
ctx.io.on('connect', socket => {
// Create a new context assigned to each connected socket
const createContext = extra => {
return Object.assign({}, socket.client.request, ctx, extra);
};
// Attach a `socket.on('name', cb)` to each of the callbacks
for (let path in listeners) {
if (path !== 'connect') {
listeners[path].forEach(cb => {
socket.on(path, data => cb(createContext({ path, socket, data })));
});
}
}
// This is not a callback and should be called straight away since we are
// already inside `io.on('connect')`
const path = 'connect';
if (listeners['connect']) {
listeners[path].forEach(cb => cb(createContext({ path, socket })));
}
});
}
};