Browse Source

Configurable cache heuristic

master
Kornel Lesiński 9 years ago
committed by Kornel Lesiński
parent
commit
23d6cd768b
  1. 3
      README.md
  2. 6
      index.js

3
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.

6
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;

Loading…
Cancel
Save