All files / spirit-common/lib/middleware if-modified.js

100% Statements 23/23
100% Branches 17/17
100% Functions 3/3
100% Lines 22/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 55 56 57 58 59 60 61 62 63 64 65                                          1x   1x 1x     1x 9x 9x     9x 2x     7x   7x 7x 7x 3x 1x       2x       5x 4x 4x 4x     5x 3x       5x      
"use strict";
 
/*
 * A middleware for handling requests with headers:
 * - If-Modified-Since
 * - If-None-Match
 *
 * If the response has a Last-Modified and matches, or
 * If the response has ETag header and matches,
 *
 * Then a 304 status is sent with the response body stripped
 *
 * NOTE: This does not generate the response headers, as
 * Last-Modified can vary depending on the resource. Also true
 * for etags, and the method of generating ETags can vary
 * depending on implementation.
 *
 * However matching is always the same.
 *
 */
 
var _require$node = require("spirit").node;
 
var is_response = _require$node.is_response;
var Response = _require$node.Response;
 
 
module.exports = function (handler) {
  return function (request) {
    return handler(request).then(function (response) {
      // typically if the response is not a 200 or 2xx response
      // then this should not 304 even if match
      if (is_response(response) === false || response.status < 200 || response.status > 299) {
        return response;
      }
 
      var match = false;
 
      var if_etag = request.headers["if-none-match"];
      var etag = Response.get(response, "ETag");
      if (if_etag !== undefined) {
        if (if_etag === etag) {
          match = true;
        } else {
          // request etag provided, but mismatch (rfc)
          // means ignore if-modified header, so return here
          return response;
        }
      }
 
      if (match === false) {
        var if_mod = new Date(request.headers["if-modified-since"]).getTime();
        var mod = new Date(Response.get(response, "Last-Modified")).getTime();
        if (isNaN(if_mod) === false && mod === if_mod) match = true;
      }
 
      if (match === true) {
        response.status = 304;
        //response.body = undefined
      }
 
      return response;
    });
  };
};