UNPKG

1.99 kBJavaScriptView Raw
1'use strict';
2
3const isString = require('lodash/isString');
4const isUndefined = require('lodash/isUndefined');
5const isObject = require('lodash/isObject');
6const isArray = require('lodash/isArray');
7const isFunction = require('lodash/isFunction');
8const uuid = require('uuid/v4');
9
10/**
11 * Generates a JSON-RPC 1.0 or 2.0 request
12 * @param {String} method Name of method to call
13 * @param {Array|Object} params Array of parameters passed to the method as specified, or an object of parameter names and corresponding value
14 * @param {String|Number|null} [id] Request ID can be a string, number, null for explicit notification or left out for automatic generation
15 * @param {Object} [options]
16 * @param {Number} [options.version=2] JSON-RPC version to use (1 or 2)
17 * @param {Function} [options.generator] Passed the request, and the options object and is expected to return a request ID
18 * @throws {TypeError} If any of the parameters are invalid
19 * @return {Object} A JSON-RPC 1.0 or 2.0 request
20 * @memberOf Utils
21 */
22const generateRequest = function(method, params, id, options) {
23 if(!isString(method)) {
24 throw new TypeError(method + ' must be a string');
25 }
26
27 options = options || {};
28
29 const request = {
30 method: method
31 };
32
33 // assume that we are doing a 2.0 request unless specified differently
34 if(isUndefined(options.version) || options.version !== 1) {
35 request.jsonrpc = '2.0';
36 }
37
38 if(params) {
39
40 // params given, but invalid?
41 if(!isObject(params) && !isArray(params)) {
42 throw new TypeError(params + ' must be an object, array or omitted');
43 }
44
45 request.params = params;
46
47 }
48
49 // if id was left out, generate one (null means explicit notification)
50 if(typeof(id) === 'undefined') {
51 const generator = isFunction(options.generator) ? options.generator : function() { return uuid(); };
52 request.id = generator(request, options);
53 } else {
54 request.id = id;
55 }
56
57 return request;
58};
59
60module.exports = generateRequest;