Skip to content

Commit

Permalink
Misc tweaks to ensure ideal state for middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
avoidwork committed Jul 26, 2017
1 parent 0a057ee commit 18ca202
Show file tree
Hide file tree
Showing 4 changed files with 2,527 additions and 27 deletions.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const path = require("path"),
ETag = require(path.join(__dirname, "lib", "etag.js"));

function factory (config) {
let obj = new ETag(config);
const obj = new ETag(config);

obj.middleware = obj.middleware();

Expand Down
34 changes: 11 additions & 23 deletions lib/etag.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,6 @@ function clone (arg) {
return JSON.parse(JSON.stringify(arg, null, 0));
}

function trim (obj) {
return obj.replace(/^(\s+|\t+|\r+|\n+)|(\s+|\t+|\r+|\n+)$/g, "");
}

class ETag {
constructor ({cacheSize = max, seed = random, notify = false, onchange = () => {}} = {}) {
this.cache = lru(cacheSize);
Expand All @@ -44,36 +40,28 @@ class ETag {

return function etag (req, res, next) {
const parsed = parse(req),
implicit = regex.implicitGet.test(req.method);

let cached = obj.cache.get(obj.hash(parsed.href)),
headers;
implicit = regex.implicitGet.test(req.method),
cached = obj.cache.get(obj.hash(parsed.href));

res.on("finish", () => {
if (implicit && regex.valid.test(res.statusCode) && regex.etag.test(res._header)) {
let lheaders = {};
const headers = res.getHeaders();

each(trim(res._header).split(/\r\n/), row => {
let i = row.split(/:\s/);

if (i[1] !== undefined) {
lheaders[i[0].toLowerCase()] = i[1];
}
});

if (obj.valid(lheaders)) {
if (implicit && regex.valid.test(res.statusCode) && headers.etag !== void 0) {
if (obj.valid(headers)) {
obj.register(parsed.href, {
etag: lheaders.etag,
headers: lheaders,
etag: headers.etag,
headers: headers,
timestamp: cached ? cached.timestamp : parseInt(new Date().getTime() / 1000, 10)
});
}
}
});

if (regex.explicitGet.test(req.method) && cached && !req.headers.range && (req.headers["if-none-match"] || "") === cached.etag) {
headers = clone(cached.headers);
const headers = clone(cached.headers);

headers.age = parseInt(new Date().getTime() / 1000 - cached.timestamp, 10);
res.statusCode = 304;
res.writeHead(304, headers);
res.end("");
} else {
Expand Down Expand Up @@ -108,7 +96,7 @@ class ETag {
}

valid (headers) {
return !headers["cache-control"] || !regex.nonCachable.test(headers["cache-control"]);
return headers["cache-control"] === void 0 || !regex.nonCachable.test(headers["cache-control"]);
}
}

Expand Down
Loading

0 comments on commit 18ca202

Please sign in to comment.