forked from tedeh/jayson
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerateRequest.js
59 lines (49 loc) · 1.79 KB
/
generateRequest.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
"use strict";
const uuid = require("uuid/v4");
/**
* Generates a JSON-RPC 1.0 or 2.0 request
* @param {String} method Name of method to call
* @param {Array|Object} params Array of parameters passed to the method as specified, or an object of parameter names and corresponding value
* @param {String|Number|null} [id] Request ID can be a string, number, null for explicit notification or left out for automatic generation
* @param {Object} [options]
* @param {Number} [options.version=2] JSON-RPC version to use (1 or 2)
* @param {Function} [options.generator] Passed the request, and the options object and is expected to return a request ID
* @throws {TypeError} If any of the parameters are invalid
* @return {Object} A JSON-RPC 1.0 or 2.0 request
* @memberOf Utils
*/
const generateRequest = function (method, params, id, options) {
if (typeof method !== "string") {
throw new TypeError(method + " must be a string");
}
options = options || {};
const request = {
method: method,
};
// assume that we are doing a 2.0 request unless specified differently
if (typeof options.version === "undefined" || options.version !== 1) {
request.jsonrpc = "2.0";
}
if (params) {
// params given, but invalid?
const type = typeof params;
if (type !== "string" && type !== "object" && !Array.isArray(params)) {
throw new TypeError(params + " must be an object, array or omitted");
}
request.params = params;
}
// if id was left out, generate one (null means explicit notification)
if (typeof id === "undefined") {
const generator =
typeof options.generator === "function"
? options.generator
: function () {
return uuid();
};
request.id = generator(request, options);
} else {
request.id = id;
}
return request;
};
module.exports = generateRequest;