Upload a schema to a zone

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
type Base64 = string;
7
/**
8
 * Upload a schema to a zone
9
 *
10
 */
11
export async function main(
12
  auth: Cloudflare,
13
  zone_id: string,
14
  body: {
15
    file: {
16
      base64: Base64;
17
      type:
18
        | "image/png"
19
        | "image/jpeg"
20
        | "image/gif"
21
        | "application/pdf"
22
        | "appication/json"
23
        | "text/csv"
24
        | "text/plain"
25
        | "audio/mpeg"
26
        | "audio/wav"
27
        | "video/mp4";
28
      name: string;
29
    };
30
    kind: "openapi_v3";
31
    name?: string;
32
    validation_enabled?: "true" | "false";
33
    [k: string]: unknown;
34
  }
35
) {
36
  const url = new URL(
37
    `https://api.cloudflare.com/client/v4/zones/${zone_id}/api_gateway/user_schemas`
38
  );
39

40
  const formData = new FormData();
41
  for (const [k, v] of Object.entries(body)) {
42
    if (v !== undefined && v !== "") {
43
      if (["file"].includes(k)) {
44
        const { base64, type, name } = v as {
45
          base64: Base64;
46
          type: string;
47
          name: string;
48
        };
49
        formData.append(
50
          k,
51
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
52
            type,
53
          }),
54
          name
55
        );
56
      } else {
57
        formData.append(k, String(v));
58
      }
59
    }
60
  }
61
  const response = await fetch(url, {
62
    method: "POST",
63
    headers: {
64
      "X-AUTH-EMAIL": auth.email,
65
      "X-AUTH-KEY": auth.key,
66
      Authorization: "Bearer " + auth.token,
67
    },
68
    body: formData,
69
  });
70
  if (!response.ok) {
71
    const text = await response.text();
72
    throw new Error(`${response.status} ${text}`);
73
  }
74
  return await response.json();
75
}
76