forked from real-chocopanda/choco-jsonrpc2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
238 lines (205 loc) · 5.96 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
var sys = require('sys');
var http = require('http');
function JsonRPCServer() {
this.functions = [];
this.descriptions = [];
this.server = this.createServer();
this.error_messages = {
PARSE_ERROR: { code: -32700, message: 'Parse error.' },
INVALID_REQUEST: { code: -32600, message: 'Invalid Request.' },
METHOD_NOT_FOUND: { code: -32601, message: 'Method not found.' },
INVALID_PARAMS: { code: -32602, message: 'Invalid params.' },
INTERNAL_ERROR: { code: -32602, message: 'Internal error.' }
// -32099..-32000 User error.
};
};
/**
* Descripe a method
*
* server.desc('ping', { myParam: "string" }, {}, "string");
* server.desc('ping', { myParam: { type: "string", optional: "true" }}, { type: "string" });
*
* @param service name
* @param params
* @param returns
*/
JsonRPCServer.prototype.desc = function (service, params, returns) {
this.trace('***', 'describe: ' + service);
for (name in params) {
if ('string' == typeof(params[name])) {
params[name] = { type: params[name] };
}
}
if ('string' == typeof(returns)) {
returns = { type: returns };
}
this.descriptions[service] = { params: params, returns: returns };
};
/**
* Enable a new method
*
* server.expose('ping', function(callback) {
* //....
*
* if (err) {
* return callback(-32000, 'ping failed'); // or callback(server.error_messages.INVALID_PARAMS);
* }
*
* callback(null, 'pong');
* });
*
* @param name
* @param callack
*/
JsonRPCServer.prototype.expose = function (name, callback) {
this.trace('***', 'exposing: ' + name);
this.functions[name] = callback;
};
/**
* To ease output of logs
*
* @param direction
* @param message
*/
JsonRPCServer.prototype.trace = function (direction, message) {
sys.puts(' ' + direction + ' ' + message);
};
/**
* Start listenning http queries
*
* @param port
* @param host
*/
JsonRPCServer.prototype.listen = function(port, host) {
this.server.listen(port, host);
this.trace('***', 'Server listening on http://' + (host || '127.0.0.1') + ':' + port + '/');
};
/**
* Create an http server
*
* @return httpServer
*/
JsonRPCServer.prototype.createServer = function () {
JsonRPCServer = this;
return http.createServer(function(req, res) {
JsonRPCServer.handleRequest(req, res);
});
};
/**
* Analyse the httpQuery
*
* @param req ServerRequest
* @param res ServerResponse
*/
JsonRPCServer.prototype.handleRequest = function(req, res) {
this.trace('<--', 'accepted request');
if(req.method === 'POST') {
this.handlePOST(req, res);
}
else {
this.handleNonPOST(req, res);
}
};
/**
* Called for non post request
*
* @param req ServerRequest
* @param res ServerResponse
*/
JsonRPCServer.prototype.handleNonPOST = function(req, res) {
var SMD = {
transport: "POST",
envelope: "JSON-RPC-2.0",
contentType: "application/json",
SMDVersion: "2.0",
target: "/",
services: {}
};
for (name in JsonRPCServer.functions) {
SMD.services[name] = {
envelope: "JSON-RPC-2.0",
transport: "POST",
parameters: this.descriptions[name] ? this.descriptions[name].params : [],
returns: this.descriptions[name] ? this.descriptions[name].returns : ''
};
}
var content = JSON.stringify(SMD);
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': content.length,
'Allow': 'POST'
});
res.write(content);
res.end();
};
/**
* Analyse and execute the post request
*
* @param req ServerRequest
* @param res ServerResponse
*/
JsonRPCServer.prototype.handlePOST = function(req, res) {
var buffer = '';
req.addListener('data', function(data) {
buffer += data;
});
req.addListener('end', function(data) {
var decoded = JSON.parse(buffer);
if(!(decoded.method && decoded.params && decoded.id != 'undefined')) {
return JsonRPCServer.sendError(decoded, JsonRPCServer.error_messages.INVALID_REQUEST, res);
}
if(!JsonRPCServer.functions.hasOwnProperty(decoded.method)) {
return JsonRPCServer.sendError(decoded, JsonRPCServer.error_messages.METHOD_NOT_FOUND, res);
}
method = JsonRPCServer.functions[decoded.method];
return method(decoded.params, function(err, result) {
if (err) {
if ('object' == typeof(err)) {
return JsonRPCServer.sendError(decoded, err, res);
}
return JsonRPCServer.sendError(decoded, { code: err, message: result }, res);
}
return JsonRPCServer.sendResponse(res, {
"result": result,
"id": decoded.id || null
});
});
});
};
/**
* Format a response error JsonRPCServer2 message
*
* @param decoded the decoded query to get the id
* @param params an object with error code and error message
* @param res ServerResponse the response object
*/
JsonRPCServer.prototype.sendError = function(decoded, params, res) {
this.sendResponse(res, {
"error": {
"code": params.code,
"message": params.message
},
"id": decoded.id || null
});
};
/**
* Send a json response
*
* @param res ServerResponse The ServerResponse
* @param object object to encode in json
* @param statusCode an http status default 200
*/
JsonRPCServer.prototype.sendResponse = function(res, object, statusCode) {
object.jsonrpc = "2.0";
var content = JSON.stringify(object);
res.writeHead(statusCode || 200, {
'Content-Type': 'application/json',
'Content-Length': content.length,
'Allow': 'POST'
});
res.write(content);
res.end();
};
exports.Server = function () {
return new JsonRPCServer();
};