all files / blackbird/modules/utils/ createRequestHandler.js

20% Statements 5/25
0% Branches 0/12
0% Functions 0/4
20% Lines 5/25
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                                                                                                           
/* jshint -W058 */
const createConnection = require("./createConnection");
const R = require("ramda");
 
/**
 * HTTP status codes that don't have entities.
 */
const STATUS_WITHOUT_CONTENT = {
    100: true,
    101: true,
    204: true,
    304: true
};
 
/**
 * Binds the given app to the "request" event of the given node HTTP server
 * so that it is called whenever the server receives a new request.
 *
 * Returns the request handler function.
 */
function createRequestHandler(app) {
    return function (nodeRequest, nodeResponse) {
        const conn = createConnection(nodeRequest);
 
        Reflect.apply(conn, app, []).then(function () {
            const isHead = conn.method === "HEAD";
            const isEmpty = isHead || STATUS_WITHOUT_CONTENT[conn.status] === true;
            const headers = conn.response.headers;
            const content = conn.response.content;
 
            if (isEmpty && !isHead) {
                headers["Content-Length"] = 0;
            }
 
            if (!headers.Date) {
                headers.Date = (new Date()).toUTCString();
            }
 
            nodeResponse.writeHead(conn.status, headers);
 
            if (isEmpty) {
                nodeResponse.end();
 
                if (R.is(Function, content.destroy)) {
                    content.destroy();
                }
            } else {
                content.pipe(nodeResponse);
            }
        }, function (error) {
            conn.onError(error);
            nodeResponse.writeHead(500, {"Content-Type": "text/plain"});
            nodeResponse.end("Internal Server Error");
        });
    };
}
 
module.exports = createRequestHandler;