From 23d6cd768b1f2efb4fb97bef41d3cca692d8b738 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 31 May 2016 17:49:53 +0100 Subject: [PATCH] Configurable cache heuristic --- README.md | 3 +++ index.js | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c8f5651..b4f9a45 100644 --- a/README.md +++ b/README.md @@ -35,11 +35,14 @@ const response = { const options = { shared: true, + cacheHeuristic: 0.1, }; ``` If `options.shared` is true (default), then response is evaluated from perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is false, then response is evaluated from perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). +`options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100*0.1 = 10 days. + ### `satisfiesWithoutRevalidation(request)` If it returns `true`, then the given `request` matches the response this cache policy has been created with, and the existing response can be used without contacting the server. diff --git a/index.js b/index.js index f6f34b9..b965157 100644 --- a/index.js +++ b/index.js @@ -20,7 +20,7 @@ function parseCacheControl(header) { return cc; } -function CachePolicy(req, res, {shared} = {}) { +function CachePolicy(req, res, {shared, cacheHeuristic} = {}) { if (!res || !res.headers) { throw Error("Response headers missing"); } @@ -30,6 +30,8 @@ function CachePolicy(req, res, {shared} = {}) { this._responseTime = this.now(); this._isShared = shared !== false; + this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE + this._status = 'status' in res ? res.status : 200; this._resHeaders = res.headers; this._rescc = parseCacheControl(res.headers['cache-control']); @@ -204,7 +206,7 @@ CachePolicy.prototype = { if (this._resHeaders['last-modified']) { const lastModified = Date.parse(this._resHeaders['last-modified']); if (isFinite(lastModified) && dateValue > lastModified) { - return (dateValue - lastModified) * 0.00001; // In absence of other information cache for 1% of item's age + return (dateValue - lastModified)/1000 * this._cacheHeuristic; } } return 0;