'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 {Boolean} [options.notificationIdNull=false] When true, version 2 requests will set id to null instead of omitting it * @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 || {}; // check valid version provided const version = typeof options.version === 'number' ? options.version : 2; if (version !== 1 && version !== 2) { throw new TypeError(version + ' must be 1 or 2'); } const request = { method: method }; if(version === 2) { request.jsonrpc = '2.0'; } if(params) { // params given, but invalid? if(typeof params !== '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 if (version === 2 && id === null) { // we have a version 2 notification if (options.notificationIdNull) { request.id = null; // id will not be set at all unless option provided } } else { request.id = id; } return request; }; module.exports = generateRequest;