Skip to content
This repository has been archived by the owner on May 5, 2023. It is now read-only.

Commit

Permalink
BREAKING: return a Promise from FindProxyForURL()
Browse files Browse the repository at this point in the history
Caused by the update to `co@4`.

Still 100% backwards compatible with the callback syntax,
but you can also use Promise syntax now.
  • Loading branch information
TooTallNate committed Jun 9, 2017
1 parent ab5177f commit bc67e2f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
50 changes: 46 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

var co = require('co');
var vm = require('vm');
var parse = require('url').parse;
var thunkify = require('thunkify');
var degenerator = require('degenerator');

Expand Down Expand Up @@ -83,7 +84,7 @@ function generate (str, opts) {
var js = degenerator(str, names);

// filename of the pac file for the vm
var filename = opts && opts.filename ? opts.filename : 'proxy.pac';
var filename = (opts && opts.filename) || 'proxy.pac';

// evaluate the JS string and extract the FindProxyForURL generator function
var fn = vm.runInNewContext(js + ';FindProxyForURL', sandbox, filename);
Expand All @@ -92,9 +93,50 @@ function generate (str, opts) {
}

// return the async resolver function
var resolver = co(fn);
var resolver = co.wrap(fn);

return function FindProxyForURL (url, _host, _callback) {
let host
let callback
switch (arguments.length) {
case 3:
host = _host
callback = _callback
break;
case 2:
if (typeof _host === 'function') {
callback = _host
} else {
host = _host
}
break;
}

if (!host) {
host = parse(url).hostname;
}

return function FindProxyForURL (url, host, fn) {
resolver(url, host, fn);
const promise = resolver(url, host, callback);

if (typeof callback === 'function') {
toCallback(promise, callback)
} else {
return promise
}
};
}

function toCallback (promise, callback) {
let called = false
function resolve(rtn) {
if (called) return
called = true
callback(null, rtn)
}
function reject(err) {
if (called) return
called = true
callback(err)
}
promise.then(resolve, reject)
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "Generates an asynchronous resolver function from a PAC file",
"main": "index.js",
"dependencies": {
"co": "^3.1.0",
"co": "^4.6.0",
"degenerator": "^1.0.4",
"ip": "^1.1.5",
"netmask": "^1.0.6",
Expand Down

0 comments on commit bc67e2f

Please sign in to comment.