1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 1× 1× 1× 1× 11× 11× 10× 1× 9× 1× 10× 10× 1× 16× 10× 1× 13× 13× 13× 13× 16× 1× 13× 9× 1× 2× 1× 1× | const retry = require('retry-promise').default; const request = require('request'); const ServiceDiscovery = require('./service_discovery'); function processHttpResponsePromiseFactory(resolve, reject) { return (err, res) => { if (err) return reject(err); if (res.body && res.body.errors && res.body.errors.length) { return reject(new Error(res.body.errors[0].message)); } return resolve({ res, body: res.body }); }; } function httpRequest(options) { return new Promise((resolve, reject) => { request(options, processHttpResponsePromiseFactory(resolve, reject)); }); } function discover(hostname, requestOptions, retryOptions) { return ServiceDiscovery.discover(hostname, retryOptions) .then(serviceUrl => httpRequest(Object.assign({}, requestOptions, { baseUrl: serviceUrl, })) ); } function closure(method, hostname, path, retryOptions) { return (payload, opts) => { const options = opts ? opts : {}; // eslint-disable-line no-unneeded-ternary const requestOptions = Object.assign( { query: {}, method: 'GET', json: true, }, { method }, opts, { uri: path, body: payload, qs: options.query, } ); requestOptions.method = requestOptions.method.toUpperCase(); return retry(retryOptions, () => discover(hostname, requestOptions, retryOptions)); }; } function serviceCall(hostname, retryOptions) { return { get(path) { return closure('GET', hostname, path, retryOptions); }, post(path) { return closure('POST', hostname, path, retryOptions); }, put(path) { return closure('PUT', hostname, path, retryOptions); }, delete(path) { return closure('DELETE', hostname, path, retryOptions); }, }; } module.exports = { processHttpResponsePromiseFactory, serviceCall, }; |