Swap-Aggregator-Subgraph/node_modules/jayson/lib/generateRequest.js
Richa-iitr d211083153 Revert "Revert "added handler""
This reverts commit c36ee8c5ca.
2022-07-03 07:30:05 +05:30

58 lines
1.9 KiB
JavaScript

'use strict';
const isString = require('lodash/isString');
const isUndefined = require('lodash/isUndefined');
const isObject = require('lodash/isObject');
const isArray = require('lodash/isArray');
const isFunction = require('lodash/isFunction');
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
*/
module.exports = function(method, params, id, options) {
if(!isString(method)) {
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(isUndefined(options.version) || options.version !== 1) {
request.jsonrpc = '2.0';
}
if(params) {
// params given, but invalid?
if(!isObject(params) && !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 = isFunction(options.generator) ? options.generator : function() { return uuid(); };
request.id = generator(request, options);
} else {
request.id = id;
}
return request;
};