Refactor ETag watcher to use path-to-regexp.

Simplifies the code and makes it easier to look at.
This commit is contained in:
D. Berge
2023-11-04 10:40:05 +01:00
parent ceeaa4a8f3
commit 12307b7ae6

View File

@@ -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];
}
}