0
Put Snippet
One script reply has been approved by the moderators Verified
Created by hugo697 175 days ago Viewed 5899 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 175 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Put Snippet
8
 *
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_identifier: string,
13
  snippet_name: string,
14
  body: {
15
    files?: string;
16
    metadata?: { main_module?: string; [k: string]: unknown };
17
    [k: string]: unknown;
18
  }
19
) {
20
  const url = new URL(
21
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/snippets/${snippet_name}`
22
  );
23

24
  const formData = new FormData();
25
  for (const [k, v] of Object.entries(body)) {
26
    if (v !== undefined && v !== "") {
27
      formData.append(k, String(v));
28
    }
29
  }
30
  const response = await fetch(url, {
31
    method: "PUT",
32
    headers: {
33
      "X-AUTH-EMAIL": auth.email,
34
      "X-AUTH-KEY": auth.key,
35
      Authorization: "Bearer " + auth.token,
36
    },
37
    body: formData,
38
  });
39
  if (!response.ok) {
40
    const text = await response.text();
41
    throw new Error(`${response.status} ${text}`);
42
  }
43
  return await response.json();
44
}
45