-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathproxy.js
53 lines (47 loc) · 1.37 KB
/
proxy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var Location = require('../Location');
var createProxy = require('../utils/createProxy');
var isRegExp = require('../utils/isRegExp');
function returnTrue() {
return true;
}
/**
* A middleware that forwards requests that pass the given test function
* to the given target. If the target is not an app, it should be a string
* or options hash that is used to create a proxy.
*
* Example:
*
* var mach = require('mach');
* var app = mach.stack();
*
* // Forward all requests to example.com.
* app.use(mach.proxy, 'http://www.example.com');
*
* // Forward all requests that match "/images/*.jpg" to S3.
* app.use(mach.proxy, 'http://s3.amazon.com/my-bucket', /\/images/*.jpg/);
*
* mach.serve(app);
*/
function proxy(app, target, test) {
test = test || returnTrue;
if (isRegExp(test)) {
var pattern = test;
test = function (conn) {
return pattern.test(conn.href);
};
} else if (typeof test !== 'function') {
throw new Error('mach.proxy needs a test function');
}
var targetApp;
if (typeof target === 'function') {
targetApp = target;
} else if (typeof target === 'string' || target instanceof Location) {
targetApp = createProxy(target);
} else {
throw new Error('mach.proxy needs a target app');
}
return function (conn) {
return conn.call(test(conn) ? targetApp : app);
};
}
module.exports = proxy;