-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
81 lines (74 loc) · 2.31 KB
/
index.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
74
75
76
77
78
79
80
81
const fetch = require('node-fetch');
const {
env: { CLOUDFLARE_API_TOKEN, CLOUDFLARE_API_KEY, CLOUDFLARE_ZONE_ID, CLOUDFLARE_EMAIL },
} = require('process');
let authMethod = 'na';
switch( true ) {
case typeof CLOUDFLARE_API_TOKEN !== 'undefined' && typeof CLOUDFLARE_ZONE_ID !== 'undefined':
authMethod = 'TOKEN';
break;
case typeof CLOUDFLARE_API_KEY !== 'undefined' && typeof CLOUDFLARE_ZONE_ID !== 'undefined' && typeof CLOUDFLARE_EMAIL !== 'undefined':
authMethod = 'KEY';
break;
}
module.exports = {
onPostBuild({
utils: {
build: { failBuild },
},
}) {
if( authMethod === 'na' ) {
return failBuild(
'Could not determine auth method. Please review the plugin README file and verify your environment variables'
);
}
else if( authMethod !== 'TOKEN' && authMethod !== 'KEY' ) {
return failBuild(
"'" + authMethod + "' is not a valid Authentication Method. Please report this issue to the developer."
);
}
else {
console.log('Cloudflare ' + authMethod + ' Authentication method detected.');
}
},
async onSuccess({
utils: {
build: { failPlugin },
},
}) {
console.log('Preparing to trigger Cloudflare cache purge');
let baseUrl = `https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/purge_cache`;
let headers;
switch( authMethod ) {
case 'TOKEN':
headers = {
'Authorization': 'Bearer ' + CLOUDFLARE_API_TOKEN,
'Content-Type': 'application/json'
};
break;
case 'KEY':
headers = {
'X-Auth-Email': CLOUDFLARE_EMAIL,
'X-Auth-Key': CLOUDFLARE_API_KEY,
'Content-Type': 'application/json'
};
break;
}
let body = { purge_everything: true };
try {
const { status, statusText } = await fetch(baseUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(body),
});
if (status != 200) {
return failPlugin(
"Cloudflare cache couldn't be purged. Status: " + status + " " + statusText
);
}
console.log('Cloudflare cache purged successfully!');
} catch (error) {
return failPlugin('Cloudflare cache purge failed', { error });
}
},
};