Created
May 12, 2017 20:20
-
-
Save igelbox/02366e06d5e7d0667792ad481760d8fb to your computer and use it in GitHub Desktop.
Configure custom DNS lookuper for NodeJS' superagent package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const dns = require('dns'); | |
const superagent = require('superagent'); | |
const hostIndexes = new Map(); | |
require('./superagent-custom-lookup')(superagent, (addresses, host) => { | |
let index = hostIndexes.get(host) || 0; | |
const result = addresses[index]; | |
index = (index + 1) % addresses.length; | |
hostIndexes.set(host, index); | |
return result; | |
}); | |
(function test() { | |
superagent.get('http://test/') | |
.then(res => { | |
console.log(res.text.substr(0, 100)); | |
setTimeout(test, 1000); | |
}) | |
.catch((error) => { | |
console.error(error); | |
setTimeout(test, 1000); | |
}); | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const dns = require('dns'); | |
module.exports = function superagentCustomLookup(superagent, handler) { | |
handler = handler || ((addresses) => addresses[(Math.random() * addresses.length) | 0]); | |
function lookup(host, options, callback) { | |
if (options.all) { | |
return dns.lookup(host, options, callback); | |
} | |
options = Object.assign({}, options, { all: true }); | |
return dns.lookup(host, options, (err, addresses, family) => { | |
if (err) { | |
return callback(err, addresses, family); | |
} | |
const addr = handler(addresses, host); | |
return callback(err, addr.address, addr.family || family); | |
}); | |
} | |
for (const protocol_key of ['http:', 'https:']) { | |
const protocol = superagent.protocols[protocol_key]; | |
const request = protocol.request; | |
superagent.protocols[protocol_key] = Object.assign({}, protocol, { | |
request: function (options, cb) { | |
if (!options.lookup) { | |
options = Object.assign({}, options, { | |
lookup, | |
}) | |
} | |
return request(options, cb); | |
}, | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment