// 1. Load the request library

// Only use a direct require if you are 100% sure that:
// - Your project does not use request directly. That is without the Promise capabilities by calling require('request').
// - Any of the installed libraries use request.
// ...because Request's prototype will be patched in step 2.
/* var request = require('request'); */

// Instead use:
var stealthyRequire = require('stealthy-require');
var request = stealthyRequire(require.cache, function () {
    return require('request');
});


// 2. Add Promise support to request

var configure = require('request-promise-core/configure/request2');

configure({
    request: request,
	// Pass your favorite ES6-compatible promise implementation
    PromiseImpl: Promise,
	// Expose all methods of the promise instance you want to call on the request(...) call
    expose: [
        'then',   // Allows to use request(...).then(...)
        'catch',  // Allows to use request(...).catch(...)
        'promise' // Allows to use request(...).promise() which returns the promise instance
    ],
    // Optional: Pass a callback that is called within the Promise constructor
    constructorMixin: function (resolve, reject) {
        // `this` is the request object
        // Additional arguments may be passed depending on the PromiseImpl used
    }
});


// 3. Use request with its promise capabilities

// E.g. crawl a web page:
request('http://localhost')
    .then(function (htmlString) {
        // Process html...
	console.log("then called - process html...");
    })
    .catch(function (err) {
        // Crawling failed...
	console.log("catch called - crawling failed...");
    });
