all files / modules/middleware/ proxy.js

81.82% Statements 18/22
57.14% Branches 8/14
100% Functions 4/4
81.82% Lines 18/22
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 54                                                                        
const Location = require("../Location");
const createProxy = require("../utils/createProxy");
const 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:
 *
 *   let mach = require('mach');
 *   let 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)) {
        const pattern = test;
        test = function (conn) {
            return pattern.test(conn.href);
        };
    } else Iif (typeof test !== "function") {
        throw new Error("mach.proxy needs a test function");
    }
 
    let targetApp;
    Eif (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;