cloudflare/cloudflare-typescript

Public

mirrored from https://github.com/cloudflare/cloudflare-typescriptAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1205adb06353055816c2fd4d6d7fd433e69a262d

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/workers/script-upload.ts

69lines · modecode

1#!/usr/bin/env -S npm run tsn -T
2
3/*
4 * Generate an API token: https://developers.cloudflare.com/fundamentals/api/get-started/create-token/
5 * (Not Global API Key!)
6 *
7 * Find your account id: https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/
8 *
9 * Set these environment variables:
10 * - CLOUDFLARE_API_TOKEN
11 * - CLOUDFLARE_ACCOUNT_ID
12 */
13
14import Cloudflare from 'cloudflare';
15
16const client = new Cloudflare({
17 apiToken: process.env['CLOUDFLARE_API_TOKEN'] ?? '',
18});
19const accountID = process.env['CLOUDFLARE_ACCOUNT_ID'] ?? '';
20
21async function main() {
22 const scriptName = 'my-hello-world-script';
23 const scriptFileName = `${scriptName}.mjs`;
24 const scriptContent = `
25 export default {
26 async fetch(request, env, ctx) {
27 return new Response(env.MESSAGE, { status: 200 });
28 }
29 };
30 `;
31
32 const script: Cloudflare.Workers.Scripts.ScriptUpdateResponse = await client.workers.scripts.update(
33 scriptName,
34 {
35 account_id: accountID,
36 /*
37 * Add script content keyed by the filename
38 */
39 // @ts-ignore
40 [scriptFileName]: new File([scriptContent], scriptFileName, {
41 type: 'application/javascript+module',
42 }),
43 // @ts-ignore
44 metadata: new File(
45 [
46 JSON.stringify({
47 // https://developers.cloudflare.com/workers/configuration/multipart-upload-metadata/
48 bindings: [
49 {
50 type: 'plain_text',
51 name: 'MESSAGE',
52 text: 'Hello World!',
53 },
54 ],
55 main_module: scriptFileName,
56 }),
57 ],
58 'metadata.json',
59 {
60 type: 'application/json',
61 },
62 ),
63 },
64 );
65
66 console.log(script.id);
67}
68
69main();
70