Add operations to a zone

Add one or more operations to a zone. Endpoints can contain path variables. Host, method, endpoint will be normalized to a canoncial form when creating an operation and must be unique on the zone. Inserting an operation that matches an existing one will return the record of the already existing operation and update its last_updated date.

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
/**
7
 * Add operations to a zone
8
 * Add one or more operations to a zone. Endpoints can contain path variables. Host, method, endpoint will be normalized to a canoncial form when creating an operation and must be unique on the zone. Inserting an operation that matches an existing one will return the record of the already existing operation and update its last_updated date.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_id: string,
13
  body: {
14
    endpoint: string;
15
    host: string;
16
    method:
17
      | "GET"
18
      | "POST"
19
      | "HEAD"
20
      | "OPTIONS"
21
      | "PUT"
22
      | "DELETE"
23
      | "CONNECT"
24
      | "PATCH"
25
      | "TRACE";
26
    [k: string]: unknown;
27
  }[]
28
) {
29
  const url = new URL(
30
    `https://api.cloudflare.com/client/v4/zones/${zone_id}/api_gateway/operations`
31
  );
32

33
  const response = await fetch(url, {
34
    method: "POST",
35
    headers: {
36
      "X-AUTH-EMAIL": auth.email,
37
      "X-AUTH-KEY": auth.key,
38
      "Content-Type": "application/json",
39
      Authorization: "Bearer " + auth.token,
40
    },
41
    body: JSON.stringify(body),
42
  });
43
  if (!response.ok) {
44
    const text = await response.text();
45
    throw new Error(`${response.status} ${text}`);
46
  }
47
  return await response.json();
48
}
49