UNPKG

wreck-promisify

Version:
109 lines (98 loc) 3.84 kB
'use strict' const Wreck = require('wreck') const Promise = require('bluebird'); const symbol = Symbol.for('wreck'); // Set default configuration for Wreck and get new instance const outbound = {} outbound.wreck = Wreck.defaults({ timeout: 2000 }) const inbound = module.exports = {}; inbound.request = (method, uri, options) => { return new Promise((resolve, reject) => { outbound.wreck.request(method, uri, options, (err, res) => { if (err) { return reject(err) } outbound.wreck.read(res, {}, function (err, body) { if (err) { return reject(err) } if (body instanceof Buffer) { body = body.toString("utf8"); return resolve(body); } }) }) }) } inbound.defaults = (options) => { outbound.wreck = outbound.wreck.defaults(options) } inbound.get = (uri, options) => { return inbound.request('GET', uri, options) } inbound.post = (uri, options) => { return inbound.request('POST', uri, options) } inbound.put = (uri, options) => { return inbound.request('PUT', uri, options) } inbound.delete = (uri, options) => { return inbound.request('DELETE', uri, options) } inbound.trace = (isEnable) => { const obj = { "label": "wreck-promisify", res: {}, req: {}, timestamp: {} }; if (isEnable) { process[symbol].on('response', (err, details) => { if (!err) { if (details.hasOwnProperty("uri")) { obj.res.url = details.uri.hasOwnProperty("href") ? details.uri.href : ""; obj.res.method = details.uri.hasOwnProperty("method") ? details.uri.method : ""; //obj.res.headers = details.uri.hasOwnProperty("headers") ? details.uri.headers : ""; if (details.hasOwnProperty("res") && details.res.hasOwnProperty("headers")) { obj.res.headers = details.res.headers; } } //obj.timestamp.start = details.start; obj.timestamp.end = Date.now(); obj.timestamp.total = ((obj.timestamp.end - obj.timestamp.start) / 1000) + "seconds"; console.log("\n\r<---[Wreck Trace ****** Statistics *****]--->\n\r"); console.info(obj); console.log("\n\r <------------------------------------------->\n\r"); } if (err) { console.log("\n\r<---[Wreck API Call Error]--->\n\r"); console.error(err); console.log("\n\r <------------------------------------------->\n\r"); } }); process[symbol].on('request', (uri, options) => { obj.timestamp.start = Date.now(); var o = {}; o.o = o; var cache = []; JSON.stringify(o, function(key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // Circular reference found, discard key return; } // Store value in our collection cache.push(value); } return value; }); cache = null; obj.req.url = uri.hasOwnProperty("href") ? uri.href : ""; obj.req.method = uri.hasOwnProperty("method") ? uri.method : ""; obj.req.query = uri.hasOwnProperty("query") ? uri.query : ""; obj.req.options = cache; }); } }