Put Script Content (Workers for Platforms)

Put script content for a script uploaded to a Workers for Platforms namespace.

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
 * Put Script Content (Workers for Platforms)
8
 * Put script content for a script uploaded to a Workers for Platforms namespace.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  account_identifier: string,
13
  dispatch_namespace: string,
14
  script_name: string,
15
  CF_WORKER_BODY_PART: string,
16
  CF_WORKER_MAIN_MODULE_PART: string,
17
  body: {
18
    "<any part name>"?: string[];
19
    metadata?: {
20
      body_part?: string;
21
      main_module?: string;
22
      [k: string]: unknown;
23
    };
24
    [k: string]: unknown;
25
  }
26
) {
27
  const url = new URL(
28
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/workers/dispatch/namespaces/${dispatch_namespace}/scripts/${script_name}/content`
29
  );
30

31
  const formData = new FormData();
32
  for (const [k, v] of Object.entries(body)) {
33
    if (v !== undefined && v !== "") {
34
      formData.append(k, String(v));
35
    }
36
  }
37
  const response = await fetch(url, {
38
    method: "PUT",
39
    headers: {
40
      "CF-WORKER-BODY-PART": CF_WORKER_BODY_PART,
41
      "CF-WORKER-MAIN-MODULE-PART": CF_WORKER_MAIN_MODULE_PART,
42
      "X-AUTH-EMAIL": auth.email,
43
      "X-AUTH-KEY": auth.key,
44
      Authorization: "Bearer " + auth.token,
45
    },
46
    body: formData,
47
  });
48
  if (!response.ok) {
49
    const text = await response.text();
50
    throw new Error(`${response.status} ${text}`);
51
  }
52
  return await response.json();
53
}
54