all files / blackbird/modules/middleware/ modified.js

100% Statements 21/21
92.31% Branches 12/13
100% Functions 3/3
100% Lines 21/21
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                                                             
/* */
const stripQuotes = require("../utils/stripQuotes");
const {is} = require("ramda");
/**
 * A middleware that automatically performs content-based HTTP caching in
 * response to requests that use the If-None-Match and/or If-Modified-Since
 * headers. In order to work effectively, downstream apps must use the ETag
 * and/or Last-Modified headers.
 *
 * Example:
 *
 *   app.use(mach.modified);
 *
 *   // Send Last-Modified and ETag headers with static files.
 *   app.use(mach.file, {
 *     useLastModified: true, // this is the default
 *     useETag: true
 *   });
 */
function modified(app) {
    return function (conn) {
        return conn.run(app).then(function () {
            const request = conn.request, response = conn.response;
 
            const ifNoneMatch = request.headers["If-None-Match"];
            const etag = response.headers.ETag;
 
            if (ifNoneMatch && etag && etag === stripQuotes(ifNoneMatch)) {
                conn.status = 304;
                response.content = "";
                return;
            }
 
            const ifModifiedSince = request.headers["If-Modified-Since"];
            let lastModified = response.headers["Last-Modified"];
 
            if (ifModifiedSince && lastModified) {
                Eif (is(String, lastModified)) {
                    lastModified = Date.parse(lastModified);
                }
 
                if (lastModified <= Date.parse(ifModifiedSince)) {
                    conn.status = 304;
                    response.content = "";
                }
            }
        });
    };
}
 
module.exports = modified;