-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathindex.js
More file actions
87 lines (71 loc) · 2.38 KB
/
index.js
File metadata and controls
87 lines (71 loc) · 2.38 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var sio = require('socket.io');
var fn = function () {};
var ControllerBridge = require('compound/lib/controller-bridge');
exports.init = function (compound) {
var app = compound.app;
var io = sio(compound.server);
compound.controllerExtensions.socket = function (id) {
return io.to(id || this.req.sessionID);
};
var map = [];
compound.map.socket = function(msg, handle) {
map.push({
event: msg,
controller: handle.split('#')[0],
action: handle.split('#')[1]
});
};
var cookieParser, session;
app.stack.forEach(function(m) {
switch (m.handle.name) {
case 'cookieParser':
cookieParser = m.handle;
break;
case 'session':
session = m.handle;
break;
}
});
io.use(function (socket, next) {
var req = socket.request;
if (!req.headers.cookie) {
return next(new Error('No cookie transmitted.'));
}
req.originalUrl = '/';
cookieParser(req, null, function (err) {
if (err) return next(new Error('Error in cookie parser'));
session(req, { on: fn, end: fn }, function (err) {
if (err) return next(new Error('Error while reading session'));
next();
});
});
});
io.on('connection', function (socket) {
var req = socket.request;
socket.join(req.sessionID);
var bridge = new ControllerBridge(compound);
map.forEach(function (r) {
socket.on(r.event, function (data, callback) {
var ctl = bridge.loadController(r.controller);
delete req.session.csrfToken;
ctl.perform(r.action, {
method: 'SOCKET',
url: r.action,
app: app,
param: function(key) {
return data[key];
},
header: function() {
return null;
},
session: req.session,
sessionID: req.sessionID,
params: data,
socket: socket
}, { send: callback }, fn);
});
});
});
// You can configure socket.io at this point.
compound.emit('socket.io', io);
};