Skip to content
This repository was archived by the owner on May 28, 2023. It is now read-only.

Commit d5a7c3c

Browse files
author
Fifciuu
committed
Invalidate on only if varnish.enabled
1 parent 833158d commit d5a7c3c

File tree

1 file changed

+56
-6
lines changed

1 file changed

+56
-6
lines changed

src/api/invalidate.ts

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@ import request from 'request'
55

66
function invalidateCache (req, res) {
77
if (config.get('server.useOutputCache')) {
8-
if (req.query.tag && req.query.key) { // clear cache pages for specific query tag
9-
if (req.query.key !== config.get('server.invalidateCacheKey')) {
10-
console.error('Invalid cache invalidation key')
11-
apiStatus(res, 'Invalid cache invalidation key', 500)
12-
return
13-
}
8+
if (!req.query.key || req.query.key !== config.get('server.invalidateCacheKey')) {
9+
console.error('Invalid cache invalidation key')
10+
apiStatus(res, 'Invalid cache invalidation key', 500)
11+
return
12+
}
13+
14+
if (req.query.tag) { // clear cache pages for specific query tag
15+
1416
console.log(`Clear cache request for [${req.query.tag}]`)
1517
let tags = []
1618
if (req.query.tag === '*') {
@@ -25,6 +27,27 @@ function invalidateCache (req, res) {
2527
})) {
2628
subPromises.push(cache.invalidate(tag).then(() => {
2729
console.log(`Tags invalidated successfully for [${tag}]`)
30+
if (config.get('varnish.enabled')) {
31+
request(
32+
{
33+
uri: `http://${config.get('varnish.host')}:${config.get('varnish.port')}/`,
34+
method: "BAN",
35+
headers: {
36+
// I should change Tags -> tag
37+
"X-VS-Cache-Tags": tag
38+
}
39+
},
40+
(err, res, body) => {
41+
if (body && body.includes("200 Ban added")) {
42+
console.log(
43+
`Tags invalidated successfully for [${tag}] in the Varnish`
44+
);
45+
} else {
46+
console.error(`Couldn't ban tag: ${tag} in the Varnish`);
47+
}
48+
}
49+
);
50+
}
2851
}))
2952
} else {
3053
console.error(`Invalid tag name ${tag}`)
@@ -48,6 +71,33 @@ function invalidateCache (req, res) {
4871
});
4972
}
5073
}
74+
} else if (config.get('varnish.enabled') && req.query.ext) {
75+
const exts = req.query.ext.split(',')
76+
for (let ext of exts) {
77+
request(
78+
{
79+
uri: `http://${config.get('varnish.host')}:${config.get('varnish.port')}/`,
80+
method: "BAN",
81+
headers: {
82+
"X-VS-Cache-Ext": ext
83+
}
84+
},
85+
(err, res, body) => {
86+
if (body && body.includes("200 Ban added")) {
87+
console.log(
88+
`Cache invalidated successfully for [${ext}] in the Varnish`
89+
);
90+
} else {
91+
console.error(`Couldn't ban extension: ${ext} in the Varnish`);
92+
}
93+
}
94+
);
95+
}
96+
apiStatus(
97+
res,
98+
"Cache invalidation succeed",
99+
200
100+
);
51101
} else {
52102
apiStatus(res, 'Invalid parameters for Clear cache request', 500)
53103
console.error('Invalid parameters for Clear cache request')

0 commit comments

Comments
 (0)