ifModifiedSince method

Future<bool> ifModifiedSince(
  1. RequestContext req,
  2. ResponseContext res
)

A middleware that handles requests with an If-Modified-Since header.

This prevents the server from even having to access the cache, and plays very well with static assets.

Implementation

Future<bool> ifModifiedSince(RequestContext req, ResponseContext res) async {
  if (req.method != 'GET' && req.method != 'HEAD') {
    return true;
  }

  var modifiedSince = req.headers?.ifModifiedSince;
  if (modifiedSince != null) {
    // Check if there is a cache entry.
    for (var pattern in patterns) {
      var reqPath = _getEffectivePath(req);

      if (pattern.allMatches(reqPath).isNotEmpty &&
          _cache.containsKey(reqPath)) {
        var response = _cache[reqPath];

        //log.info('timestamp ${response?.timestamp} vs since $modifiedSince');

        if (response != null &&
            response.timestamp.compareTo(modifiedSince) <= 0) {
          // If the cache timeout has been met, don't send the cached response.
          var timeDiff =
              DateTime.now().toUtc().difference(response.timestamp);

          //log.info(
          //    'Time Diff: ${timeDiff.inMilliseconds} >=  ${timeout.inMilliseconds}');
          if (timeDiff.inMilliseconds >= timeout.inMilliseconds) {
            return true;
          }

          // Old code: res.statusCode = 304;
          // Return the response stored in the cache
          _setCachedHeaders(response.timestamp, req, res);
          res
            ..headers.addAll(response.headers)
            ..add(response.body);
          await res.close();
          return false;
        }
      }
    }
  }

  return true;
}