forked from unpkg/unpkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudflare.js
More file actions
90 lines (75 loc) · 1.92 KB
/
cloudflare.js
File metadata and controls
90 lines (75 loc) · 1.92 KB
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
82
83
84
85
86
87
88
89
90
const fetch = require('isomorphic-fetch');
const CloudflareEmail = process.env.CLOUDFLARE_EMAIL;
const CloudflareKey = process.env.CLOUDFLARE_KEY;
if (CloudflareEmail == null) {
console.error('Missing the $CLOUDFLARE_EMAIL environment variable');
process.exit(1);
}
if (CloudflareKey == null) {
console.error('Missing the $CLOUDFLARE_KEY environment variable');
process.exit(1);
}
function get(path) {
return fetch(`https://api.cloudflare.com/client/v4${path}`, {
method: 'GET',
headers: {
'X-Auth-Email': CloudflareEmail,
'X-Auth-Key': CloudflareKey
}
});
}
function getLog(zoneId, rayId) {
return get(`/zones/${zoneId}/logs/requests/${rayId}`).then(
res => (res.status === 404 ? null : res.json())
);
}
function getZone(domain) {
return get(`/zones?name=${domain}`)
.then(res => res.json())
.then(data => {
if (!data.success) throw data;
const zones = data.result;
if (zones.length > 1) {
console.error(
`Domain "${domain}" has more than one zone: ${zones.join(', ')}`
);
}
return zones[0];
});
}
function post(path, data) {
const options = {
method: 'POST',
headers: {
'X-Auth-Email': CloudflareEmail,
'X-Auth-Key': CloudflareKey
}
};
if (data) {
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(data);
}
return fetch(`https://api.cloudflare.com/client/v4${path}`, options);
}
function purgeFiles(zoneId, files) {
return post(`/zones/${zoneId}/purge_cache`, { files })
.then(res => res.json())
.then(data => {
if (data.success) return data;
throw data;
});
}
function purgeTags(zoneId, tags) {
return post(`/zones/${zoneId}/purge_cache`, { tags })
.then(res => res.json())
.then(data => {
if (data.success) return data;
throw data;
});
}
module.exports = {
getLog,
getZone,
purgeFiles,
purgeTags
};