This repository has been archived by the owner on Aug 13, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudflare.js
156 lines (141 loc) · 4.22 KB
/
cloudflare.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/* SPDX-FileCopyrightText: 2016-present Kriasoft <hello@kriasoft.com> */
/* SPDX-License-Identifier: MIT */
import envars from "envars";
import got from "got";
import minimist from "minimist";
import assert from "node:assert";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Cloudflare API client.
*
* @example
* $ yarn cf:create-test-subdomain --version #0
* $ yarn cf:delete-test-subdomain --version #0
*
* @type {import("got").Got}
*/
export const cf = got.extend({
prefixUrl: `https://api.cloudflare.com/client/v4`,
responseType: "json",
resolveBodyOnly: true,
hooks: {
beforeRequest: [
(options) => {
options.headers.authorization = `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`;
},
],
afterResponse: [
(res) => {
if (!res.body?.success) throw new Error(res.body.errors[0].message);
res.body?.messages.forEach((x) => console.log(x));
return res;
},
],
},
});
/**
* Creates or updates a temporary test subdomain in Cloudflare.
*
* @param {number | string} version
* @param {string | undefined} content
*/
export async function createTestSubdomain(version, content = "192.0.2.1") {
const { APP_ORIGIN, CLOUDFLARE_ZONE_ID } = process.env;
const name = `${version}-${new URL(APP_ORIGIN).hostname}`;
const record = { type: "A", name, content, ttl: 1, proxied: true };
// Check if the target subdomain already exists
const { result: records } = await cf.get(
`zones/${CLOUDFLARE_ZONE_ID}/dns_records?type=${record.type}&name=${record.name}`,
);
// Create or update the target subdomain
if (records.length === 0) {
console.log(`Creating ${name} subdomain...`);
await cf.post(`zones/${CLOUDFLARE_ZONE_ID}/dns_records`, {
json: record,
});
} else {
console.log(`Updating ${name} subdomain...`);
await Promise.all(
records.map(({ id }) =>
cf.patch(`zones/${CLOUDFLARE_ZONE_ID}/dns_records/${id}`, {
json: record,
}),
),
);
}
}
/**
* Deletes a temporary subdomain from Cloudflare.
*
* @param {number | string} version
*/
export async function deleteTestSubdomain(version) {
const { APP_ORIGIN, CLOUDFLARE_ZONE_ID } = process.env;
const name = `${version}-${new URL(APP_ORIGIN).hostname}`;
const { result: records } = await cf.get(
`zones/${CLOUDFLARE_ZONE_ID}/dns_records?type=A&name=${name}`,
);
return Promise.all(
records.map((record) =>
cf.delete(`zones/${CLOUDFLARE_ZONE_ID}/dns_records/${record.id}`),
),
);
}
export async function listNamespaces() {
const { CLOUDFLARE_ACCOUNT_ID } = process.env;
let page = 0;
let result = [];
while (++page < 15) {
const res = await cf.get(
`accounts/${CLOUDFLARE_ACCOUNT_ID}/storage/kv/namespaces?page=${page}&per_page=50`,
);
result = [...result, ...res.result];
if (res.result_info.total_pages === page) {
break;
}
}
return result;
}
/**
* Deletes a temporary KV Storage Namespace from Cloudflare.
*
* @param {number | string} version
*/
export async function deleteTestKVNamespace(version) {
const { CLOUDFLARE_ACCOUNT_ID } = process.env;
const namespaces = await listNamespaces();
const ns = namespaces.find((x) => x.title.endsWith(`_${version}`));
if (ns) {
await cf.delete(
`accounts/${CLOUDFLARE_ACCOUNT_ID}/storage/kv/namespaces/${ns.id}`,
);
}
}
// Execute one of the commands when the script is launched directly
if (import.meta.url === `file://${process.argv[1]}`) {
// Load environment variables (CLOUDFLARE_ACCOUNT_ID, etc.)
const args = minimist(process.argv.slice(2));
envars.config({
env: args.env || "test",
cwd: path.resolve(__dirname, "../env"),
});
let cmd;
switch (args._[0]) {
case "create-test-subdomain":
assert(args.version, "Missing --version argument");
cmd = createTestSubdomain(args.version);
break;
case "delete-test-subdomain":
assert(args.version, "Missing --version argument");
cmd = deleteTestSubdomain(args.version);
break;
default:
cmd = Promise.reject(`Unknown command name: ${args._[0]}`);
}
cmd.catch((err) => {
console.error(err);
process.exit(1);
});
}