Convert args array or object into a normalized value object. Suppoorts extra options and(or) callback parameters. Per the Promise API feature promisifyAll (see also sb-promisify), the callback (if provided) must always be last. @arg {Array|object} args - User-provided parameter object or
(args, defParams, methodName = 'method', optionsFormatter = null)
| 36 | @example api.processArgs(args, ['account'], 'contract', optionsFormatter) |
| 37 | */ |
| 38 | function processArgs (args, defParams, methodName = 'method', optionsFormatter = null) { |
| 39 | let params = {} |
| 40 | let options = {} |
| 41 | |
| 42 | const expectedArgCount = defParams.length |
| 43 | |
| 44 | // Extra callback argument? Last per promisifyAll standard. |
| 45 | let callbackArg |
| 46 | if (typeof args[args.length - 1] === 'function') { |
| 47 | callbackArg = args[args.length - 1] |
| 48 | args = args.slice(0, args.length - 1) |
| 49 | } |
| 50 | |
| 51 | let callback |
| 52 | let returnPromise |
| 53 | if(callbackArg) { |
| 54 | callback = function(err, result) { |
| 55 | if(err) { |
| 56 | callbackArg(err) |
| 57 | } else { |
| 58 | callbackArg(null, result) |
| 59 | } |
| 60 | } |
| 61 | } else { |
| 62 | returnPromise = new Promise((resolve, reject) => { |
| 63 | callback = function(err, result) { |
| 64 | if(err) { |
| 65 | reject(err) |
| 66 | } else { |
| 67 | resolve(result) |
| 68 | } |
| 69 | } |
| 70 | }) |
| 71 | } |
| 72 | |
| 73 | // Look for the options parameter (after potential callback was removed) |
| 74 | if(typeof optionsFormatter === 'function' && args.length > 0 && |
| 75 | ((typeof args[0] === 'object' && args.length === 2) || args.length === expectedArgCount + 1) |
| 76 | ) { |
| 77 | //An extra options argument |
| 78 | options = optionsFormatter(args[args.length - 1]) |
| 79 | if(options != null) { |
| 80 | // It is valid, remove it to avoid parameter count an error below |
| 81 | args = args.slice(0, args.length - 1) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | // Parameteters (args) can be ordered or an object |
| 86 | if (args.length === 1 && typeof args[0] === 'object') { |
| 87 | params = args[0] |
| 88 | } else { |
| 89 | // give ordered paramaters names |
| 90 | |
| 91 | if (args.length > expectedArgCount) { |
| 92 | // console.log('typeof defParams[expectedArgCount]', args) |
| 93 | throw new TypeError(`${methodName} is expecting ${ |
| 94 | expectedArgCount} parameters but ${ |
| 95 | args.length} where provided`) |
no test coverage detected