-
Notifications
You must be signed in to change notification settings - Fork 0
/
purge-cdn-cache.js
74 lines (66 loc) · 2.32 KB
/
purge-cdn-cache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const axios = require('axios');
const fs = require('fs');
const parameters = JSON.parse(process.env.PARAMETERS);
const CLOUDFLARE_X_AUTH_EMAIL = parameters.Parameters
.find(param => param.Name === 'CLOUDFLARE_X_AUTH_EMAIL').Value;
const CLOUDFLARE_X_AUTH_KEY = parameters.Parameters
.find(param => param.Name === 'CLOUDFLARE_X_AUTH_KEY').Value;
const CLOUDFLARE_ZONE_ID = parameters.Parameters
.find(param => param.Name === 'CLOUDFLARE_ZONE_ID').Value;
const headers = {
'X-Auth-Email': CLOUDFLARE_X_AUTH_EMAIL,
'X-Auth-Key': CLOUDFLARE_X_AUTH_KEY,
'Content-Type': 'application/json'
};
const urls = fs.readFileSync('urls-to-purge.txt', 'utf8')
.toString()
.split('\n')
.map(line => line.trim());
if (urls.length === 0 || (urls.length === 1 && !urls[0])) {
return;
}
let body, isAll = false;
if (urls.length === 1 && urls[0] === 'All') {
body = { purge_everything: true};
isAll = true;
} else if (urls.length > 0) {
body = { files: urls.reduce((acc, curr) => {
if (curr === '') {
return acc;
} else if (curr.toLowerCase() === 'all posts') {
const allPosts = getPostsURLs();
acc.push(...allPosts);
} else {
const path = curr === '/' ? '' : curr;
acc.push(`https://www.kabardinovd.com${path}`);
acc.push(`https://kabardinovd.com${path}`);
}
return acc;
}, []) };
}
axios
.post(`https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/purge_cache`, body, {headers})
.then(() => {
fs.writeFileSync('deploy-logs.txt', `
Busted cache for the following urls:
${isAll ? 'All of them' : urls.join(', ')}
`);
})
.catch((error) => {
fs.writeFileSync('deploy-logs.txt', `
error: ${JSON.stringify(error)}
`);
})
function getPostsURLs() {
const files = fs.readdirSync('posts');
return files
.filter((fileNameWithExt) =>
fileNameWithExt.split('.').pop()
.toLowerCase() !== 'json')
.flatMap(fileNameWithExt => {
const withoutExt = fileNameWithExt
.split('.').slice(0, -1).join('.');
return [`https://kabardinovd.com/posts/${withoutExt}/`,
`https://www.kabardinovd.com/posts/${withoutExt}/`]
});
}