all files / blackbird/modules/ Connection.js

91.86% Statements 79/86
84.85% Branches 56/66
80% Functions 16/20
91.86% Lines 79/86
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186      34×                                 139×   139× 139× 43× 96×     139× 139× 139×   139× 139× 139× 139×     139×         139× 139× 139× 139×   139× 139×       44×       142×       127×       139×                                               86×                             199×   199×   199× 199× 196× 131×     65× 60× 45×   15× 14×     15×     15× 11×                                      
/* jshint -W058 */
const d = require("describe-property");
const isBinary = require("bodec").isBinary;
const decodeBase64 = require("./utils/decodeBase64");
const encodeBase64 = require("./utils/encodeBase64");
const stringifyQuery = require("./utils/stringifyQuery");
const Promise = require("./utils/Promise");
const Location = require("./Location");
const Message = require("./Message");
const R = require("ramda"),
    {is} = R;
 
function locationPropertyAlias(name) {
    return d.gs(function () {
        return this.location[name];
    }, function (value) {
        this.location[name] = value;
    });
}
 
function defaultErrorHandler(error) {
    if (typeof console !== "undefined" && console.error) {
        console.error(error && error.stack || error);
    } else {
        throw error; // Don't silently swallow errors!
    }
}
 
function defaultCloseHandler() {}
 
function defaultApp(conn) {
    conn.status = 404;
    conn.response.contentType = "text/plain";
    conn.response.content = `Not found: ${conn.method} ${conn.path}`;
}
 
class Connection {
    constructor(opts) {
        const options = opts || {};
 
        let location;
        if (is(String, options)) {
            location = options; // options may be a URL string.
        } else if (options.location || options.url) {
            location = options.location || options.url;
        }
 
        this.location = location;
        this.version = options.version || "1.1";
        this.method = options.method;
 
        this.onError = (options.onError || defaultErrorHandler).bind(this);
        this.onClose = (options.onClose || defaultCloseHandler).bind(this);
        this.request = new Message(options.content, options.headers);
        this.response = new Message();
 
      // Params may be given as an object.
        if (options.params) {
            if (this.method === "GET" || this.method === "HEAD") {
                this.query = options.params;
            } else {
                this.request.contentType = "application/x-www-form-urlencoded";
                this.request.content = stringifyQuery(options.params);
            }
        }
 
        this.withCredentials = options.withCredentials || false;
        this.remoteHost = options.remoteHost || null;
        this.remoteUser = options.remoteUser || null;
        this.basename = "";
 
        this.responseText = null;
        this.status = 200;
    }
 
    get method() {
        return this._method;
    }
 
    set method(value) {
        this._method = is(String, value) ? value.toUpperCase() : "GET";
    }
 
    get location() {
        return this._location;
    }
 
    set location(value) {
        this._location = is(Location, value) ? value : new Location(value);
    }
 
    get isSSL() {
        return this.protocol === "https:";
    }
 
    get auth() {
        const header = this.request.headers.Authorization;
 
        if (header) {
            const parts = header.split(" ", 2);
            const scheme = parts[0];
 
            Eif (scheme.toLowerCase() === "basic") {
                return decodeBase64(parts[1]);
            }
 
            return header;
        }
 
        return this.location.auth;
    }
 
    set auth(value) {
        const headers = this.request.headers;
 
        Eif (value && typeof value === "string") {
            headers.Authorization = `Basic ${encodeBase64(value)}`;
        } else {
            Reflect.deleteProperty(headers, "Authorization");
        }
    }
 
    get pathname() {
        return this.location.pathname.replace(this.basename, "") || "/";
    }
 
    set pathname(value) {
        this.location.pathname = this.basename + value;
    }
 
    get path() {
        return this.pathname + this.search;
    }
 
    set path(value) {
        this.location.path = this.basename + value;
    }
 
    run(a) {
        const app = a || defaultApp;
 
        const conn = this;
 
        try {
            return Promise.resolve(app(conn)).then(function (value) {
                if (R.isNil(value)) {
                    return;
                }
 
                if (is(Number, value)) {
                    conn.status = value;
                } else if (is(String, value) || isBinary(value) || is(Function, value.pipe)) {
                    conn.response.content = value;
                } else {
                    if (!R.isNil(value.headers)) {
                        conn.response.headers = value.headers;
                    }
 
                    if (!R.isNil(value.content)) {
                        conn.response.content = value.content;
                    }
 
                    if (!R.isNil(value.status)) {
                        conn.status = value.status;
                    }
                }
            });
        } catch (error) {
            return Promise.reject(error);
        }
    }
}
 
Object.defineProperties(Connection.prototype, {
    href: locationPropertyAlias("href"),
    protocol: locationPropertyAlias("protocol"),
    host: locationPropertyAlias("host"),
    hostname: locationPropertyAlias("hostname"),
    port: locationPropertyAlias("port"),
    search: locationPropertyAlias("search"),
    queryString: locationPropertyAlias("queryString"),
    query: locationPropertyAlias("query")
});
 
module.exports = Connection;