(methodName, url, definition, config)
| 44 | } |
| 45 | |
| 46 | function fetchMethod (methodName, url, definition, config) { |
| 47 | const {logger} = config |
| 48 | |
| 49 | return function (...args) { |
| 50 | if (args.length === 0) { |
| 51 | console.log(usage(methodName, definition)) |
| 52 | return |
| 53 | } |
| 54 | |
| 55 | const optionsFormatter = option => { |
| 56 | if(typeof option === 'boolean') { |
| 57 | return {broadcast: option} |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | const processedArgs = processArgs(args, Object.keys(definition.params || []), methodName, optionsFormatter) |
| 62 | |
| 63 | const {params, options, returnPromise} = processedArgs |
| 64 | let {callback} = processedArgs |
| 65 | |
| 66 | const body = JSON.stringify(params) |
| 67 | if (logger.log) { |
| 68 | logger.log('api >', 'post', '\t', url, body) |
| 69 | } |
| 70 | const fetchConfiguration = {body, method: 'POST'} |
| 71 | Object.assign(fetchConfiguration, config.fetchConfiguration) |
| 72 | |
| 73 | fetch(url, fetchConfiguration).then(response => { |
| 74 | if (response.status >= 200 && response.status < 300) { |
| 75 | return response.json() |
| 76 | } else { |
| 77 | return response.text().then(bodyResp => { |
| 78 | const error = new Error(bodyResp) |
| 79 | error.status = response.status |
| 80 | error.statusText = response.statusText |
| 81 | throw error |
| 82 | }) |
| 83 | } |
| 84 | }).then(objectResp => { |
| 85 | if (logger.log) { |
| 86 | logger.log('api <', 'response', '\t', url, JSON.stringify(objectResp)) |
| 87 | } |
| 88 | try { |
| 89 | callback(null, objectResp) |
| 90 | } catch(callbackError) { |
| 91 | if(logger.error) { |
| 92 | logger.error('api <', 'result callback', ':', callbackError) |
| 93 | } |
| 94 | } |
| 95 | }) |
| 96 | .catch(error => { |
| 97 | let message = '' |
| 98 | try { |
| 99 | // nodeos format (fail safe) |
| 100 | message = JSON.parse(error.message).error.details[0] |
| 101 | } catch(e2) {} |
| 102 | |
| 103 | if(logger.error) { |
no test coverage detected