all files / modules/middleware/ gzip.js

100% Statements 19/19
100% Branches 8/8
100% Functions 4/4
100% Lines 19/19
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                                          
const zlib = require("zlib");
const mach = require("../index");
 
mach.extend(
  require("../extensions/acceptEncoding")
);
 
const GZIP_MATCHER = /text|javascript|json/i;
 
function shouldGzipContentType(contentType) {
    if (!contentType || contentType === "text/event-stream") {
        return false;
    }
 
    return GZIP_MATCHER.test(contentType);
}
 
/**
 * A middleware that gzip's the response content (see http://www.gzip.org/).
 * Options may be any of node's zlib options (see http://nodejs.org/api/zlib.html).
 */
function gzip(app, options) {
    return function (conn) {
        return conn.call(app).then(function () {
            const response = conn.response;
            const headers = response.headers;
 
            if (shouldGzipContentType(headers["Content-Type"]) && conn.acceptsEncoding("gzip")) {
                response.content = response.content.pipe(zlib.createGzip(options));
 
                delete headers["Content-Length"];
                headers["Content-Encoding"] = "gzip";
                headers.Vary = "Accept-Encoding";
            }
        });
    };
}
 
module.exports = gzip;