-
Notifications
You must be signed in to change notification settings - Fork 15
/
lib.js
109 lines (89 loc) · 3.54 KB
/
lib.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
var DDPServer = function(opts) {
var WebSocket = require('faye-websocket'),
http = require('http'),
_ = require('underscore'),
server = opts.server || http.createServer(),
methods = {},
self = this;
if (opts.methods) _.extend(methods, opts.methods);
server.on('upgrade', function(request, socket, body) {
function sendMessage(data) {
ws.send(JSON.stringify(data));
}
if (WebSocket.isWebSocket(request)) {
var ws = new WebSocket(request, socket, body);
var session_id = new Date().getTime();
ws.on('message', function(event) {
var data = JSON.parse(event.data);
switch (data.msg) {
case "connect":
{
sendMessage({
server_id: 0
});
sendMessage({
msg: "connected",
session_id: session_id
});
break;
}
case "method":
{
if (data.method in methods) {
try {
var result = methods[data.method].apply(this, data.params);
sendMessage({
result: result,
id: data.id,
msg: "result"
});
} catch (e) {
sendMessage({
id: data.id,
error: {
error: 500,
reason: "Internal Server Error",
errorType: "Meteor.Error"
}
});
}
} else {
console.log("Error method " + data.method + " not found");
sendMessage({
id: data.id,
error: {
error: 404,
reason: "Method not found",
errorType: "Meteor.Error"
}
});
}
break;
}
default:
{
}
}
});
ws.on('close', function(event) {
console.log('close', event.code, event.reason);
ws = null;
session_id = null;
});
}
});
this.listen = function(port) {
// assumed that .listen() should be called outside, if server is passed in options
if (opts.server) {
return;
}
server.listen(port);
};
this.methods = function(newMethods) {
for (var key in newMethods) {
if (key in methods) throw new Error(500, "A method named " + key + " already exists");
}
_.extend(methods, newMethods);
};
};
module.exports = DDPServer;