From 12307b7ae65fd4288c8390dd985906782e17ecaa Mon Sep 17 00:00:00 2001 From: "D. Berge" Date: Sat, 4 Nov 2023 10:40:05 +0100 Subject: [PATCH] Refactor ETag watcher to use path-to-regexp. Simplifies the code and makes it easier to look at. --- lib/www/server/api/middleware/etag/watch.js | 46 ++++++++------------- 1 file changed, 17 insertions(+), 29 deletions(-) diff --git a/lib/www/server/api/middleware/etag/watch.js b/lib/www/server/api/middleware/etag/watch.js index 09914f7..d76cc11 100644 --- a/lib/www/server/api/middleware/etag/watch.js +++ b/lib/www/server/api/middleware/etag/watch.js @@ -1,3 +1,4 @@ +const pathToRegExp = require("path-to-regexp"); const { getCache } = require('./cache'); const { listen } = require('../../../lib/db/notify'); const channels = require('../../../lib/db/channels'); @@ -9,38 +10,27 @@ const rels = [ }, { channels: [ "event" ], - urls: [ /^\/project\/([^\/]+)\/event/ ], - matches: [ "project" ] + urls: [ "/project/:project/event" ], }, { channels: [ "project" ], - urls: [ /^\/project\/([^\/]+)\// ], - matches: [ "project" ] + urls: [ "/project/:project" ] }, { channels: [ "preplot_lines", "preplot_points" ], - urls: [ /^\/project\/([^\/]+)\/line[\/?]?/ ], - matches: [ "project" ] + urls: [ "/project/:project/line" ] }, { channels: [ "planned_lines" ], - urls: [ /^\/project\/([^\/]+)\/plan[\/?]?/ ], - matches: [ "project" ] + urls: [ "/project/:project/plan" ] }, { - channels: [ "raw_lines", "raw_shots" ], - urls: [ /^\/project\/([^\/]+)\/sequence[\/?]?/ ], - matches: [ "project" ] - }, - { - channels: [ "final_lines", "final_shots" ], - urls: [ /^\/project\/([^\/]+)\/sequence[\/?]?/ ], - matches: [ "project" ] + channels: [ "raw_lines", "raw_shots", "final_lines", "final_shots" ], + urls: [ "/project/:project/sequence" ] }, { channels: [ "info" ], urls: [ ], - matches: [ ], callback (url, data) { if (data.payload?.table == "info") { const pid = data.payload?.pid; @@ -84,19 +74,17 @@ function invalidateCache (data, cache) { for (let rel of rels) { if (rel.channels.includes(channel)) { for (let url of rel.urls) { + + const matches = typeof url === "function" + ? url + : pathToRegExp.match(url, {decode: decodeURIComponent, end: false}); + for (let [key, data] of Object.entries(cache)) { - const match = key.match(url)?.slice(1); - if (match) { - if (rel.matches) { - if (rel.matches.every( (field, idx) => match[idx] == fields[field] )) { - console.log("DELETE ENTRY (MATCHES)", key); - delete cache[key]; - } - } else { - // Delete unconditionally - console.log("DELETE ENTRY (UNCONDITIONAL)", key); - delete cache[key]; - } + + const { params } = matches(key); + + if (params && Object.entries(params).every(i => fields[i[0]] == i[1])) { + delete cache[key]; } }