responseFinalizer method
A response finalizer that saves responses to the cache.
Implementation
Future<bool> responseFinalizer(
RequestContext req, ResponseContext res) async {
if (res.statusCode == 304) {
return true;
}
if (req.method != 'GET' && req.method != 'HEAD') {
return true;
}
// Check if there is a cache entry.
for (var pattern in patterns) {
var reqPath = _getEffectivePath(req);
if (pattern.allMatches(reqPath).isNotEmpty) {
var now = DateTime.now().toUtc();
// Invalidate the response, if need be.
if (_cache.containsKey(reqPath)) {
// If there is no timeout, don't invalidate.
//if (timeout == null) return true;
// Otherwise, don't invalidate unless the timeout has been exceeded.
var response = _cache[reqPath];
if (response == null ||
now.difference(response.timestamp) < timeout) {
return true;
}
// If the cache entry should be invalidated, then invalidate it.
purge(reqPath);
}
// Save the response.
var writeLock = _writeLocks.putIfAbsent(reqPath, () => Pool(1));
await writeLock.withResource(() {
if (res.buffer != null) {
_cache[reqPath] = _CachedResponse(
Map.from(res.headers), res.buffer!.toBytes(), now);
}
});
_setCachedHeaders(now, req, res);
}
}
return true;
}