client.js
2.66 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
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
var util = require('./util');
var defaultConfig = {};
function Client(options) {
this.options = options =
util.clone(util.defaults(options || {}, defaultConfig));
if (!options.server) {
throw 'The server config option is required';
}
this._server = options.server;
this._nextId = 0;
}
Client.prototype._makeRequest = function () {
var method, params, callback, id;
var args = Array.prototype.slice.call(arguments);
var lastArg = args.length - 1;
var request = {
jsonrpc: '2.0'
};
if (util.isObject(args[0]) &&
!util.isUndefined(args[0]) && !util.isNull(args[0])
) {
// called with a config object
method = args[0].method;
params = args[0].params;
request.callback = args[0].callback;
} else {
// called with a method name and optional params and callback
method = args[0];
params = args.slice(1);
}
if (!util.isString(method)) {
throw 'Method must be a string';
}
if (params === null ||
(!util.isArray(params) && !util.isObject(params))
) {
throw 'Params must be an object or array';
}
request.method = method;
if (params) {
request.params = params;
}
return request;
};
Client.prototype._send = function (request, callback) {
try {
request = JSON.stringify(request);
} catch (e) {
throw 'Could not serialize request to JSON';
}
if (callback) {
this._server.respond(request, function (error, response) {
callback(error, JSON.parse(response));
});
} else {
this._server.respond(request);
}
};
Client.prototype.request = function () {
var request = this._makeRequest.apply(this, arguments);
var callback;
var response;
request.id = this._nextId++;
if (request.callback) {
callback = request.callback;
delete request.callback;
} else if (util.isArray(request.params) &&
util.isFunction(request.params[request.params.length - 1])
) {
callback = request.params.pop();
}
this._send(request, function (error, response) {
if (callback) {
if (error) {
return callback(error, null);
}
callback(response.error || null, response.result || null);
}
});
};
Client.prototype.notify = function () {
var request = this._makeRequest.apply(this, arguments);
delete request.callback;
this._send(request);
};
function parseArgs(args) {
args = args.split(/,\s*/);
var result = {};
for (var i = 0; i < args.length; i++) {
result[args[i]] = i;
}
return result;
}
function keys(o) {
if (Object.prototype.keys) {
return o.keys();
}
var result = [];
for (var k in o) {
if (o.hasOwnProperty(k)) {
result.push(k);
}
}
return result;
}
module.exports = Client;