* Returns a function that creates the loader for * either `ws` or `web`'s passes. * * Examples: * * httpProxy.createRightProxy('ws') * // => [Function] * * @param {String} Type Either 'ws' or 'web' * * @return {Function} Loader Function that when called returns an iterator for the
(type)
| 26 | */ |
| 27 | |
| 28 | function createRightProxy(type) { |
| 29 | |
| 30 | return function(options) { |
| 31 | return function(req, res /*, [head], [opts] */) { |
| 32 | var passes = (type === 'ws') ? this.wsPasses : this.webPasses, |
| 33 | args = [].slice.call(arguments), |
| 34 | cntr = args.length - 1, |
| 35 | head, cbl; |
| 36 | |
| 37 | /* optional args parse begin */ |
| 38 | if(typeof args[cntr] === 'function') { |
| 39 | cbl = args[cntr]; |
| 40 | |
| 41 | cntr--; |
| 42 | } |
| 43 | |
| 44 | var requestOptions = options; |
| 45 | if( |
| 46 | !(args[cntr] instanceof Buffer) && |
| 47 | args[cntr] !== res |
| 48 | ) { |
| 49 | //Copy global options |
| 50 | requestOptions = extend({}, options); |
| 51 | //Overwrite with request options |
| 52 | extend(requestOptions, args[cntr]); |
| 53 | |
| 54 | cntr--; |
| 55 | } |
| 56 | |
| 57 | if(args[cntr] instanceof Buffer) { |
| 58 | head = args[cntr]; |
| 59 | } |
| 60 | |
| 61 | /* optional args parse end */ |
| 62 | |
| 63 | ['target', 'forward'].forEach(function(e) { |
| 64 | if (typeof requestOptions[e] === 'string') |
| 65 | requestOptions[e] = parse_url(requestOptions[e]); |
| 66 | }); |
| 67 | |
| 68 | if (!requestOptions.target && !requestOptions.forward) { |
| 69 | return this.emit('error', new Error('Must provide a proper URL as target')); |
| 70 | } |
| 71 | |
| 72 | for(var i=0; i < passes.length; i++) { |
| 73 | /** |
| 74 | * Call of passes functions |
| 75 | * pass(req, res, options, head) |
| 76 | * |
| 77 | * In WebSockets case the `res` variable |
| 78 | * refer to the connection socket |
| 79 | * pass(req, socket, options, head) |
| 80 | */ |
| 81 | if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop |
| 82 | break; |
| 83 | } |
| 84 | } |
| 85 | }; |