cloudflare/cloudflare-typescript
Publicmirrored fromhttps://github.com/cloudflare/cloudflare-typescriptAvailable
examples/workers/script-upload.ts
157lines ยท modecode
| 1 | #!/usr/bin/env -S npm run tsn -T |
| 2 | |
| 3 | /** |
| 4 | * Create and deploy a Worker |
| 5 | * |
| 6 | * Docs: |
| 7 | * - https://developers.cloudflare.com/workers/configuration/versions-and-deployments/ |
| 8 | * - https://developers.cloudflare.com/workers/platform/infrastructure-as-code/ |
| 9 | * |
| 10 | * Prerequisites: |
| 11 | * 1. Generate an API token: https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ |
| 12 | * 2. Find your account ID: https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/ |
| 13 | * 3. Find your workers.dev subdomain: https://developers.cloudflare.com/workers/configuration/routing/workers-dev/ |
| 14 | * |
| 15 | * Environment variables: |
| 16 | * - CLOUDFLARE_API_TOKEN (required) |
| 17 | * - CLOUDFLARE_ACCOUNT_ID (required) |
| 18 | * - CLOUDFLARE_SUBDOMAIN (optional) |
| 19 | * |
| 20 | * Usage: |
| 21 | * Run this script to deploy a simple "Hello World" Worker. |
| 22 | * Access it at: my-hello-world-worker.$subdomain.workers.dev |
| 23 | */ |
| 24 | |
| 25 | import { exit } from 'node:process'; |
| 26 | |
| 27 | import Cloudflare from 'cloudflare'; |
| 28 | |
| 29 | interface Config { |
| 30 | apiToken: string; |
| 31 | accountId: string; |
| 32 | subdomain: string | undefined; |
| 33 | workerName: string; |
| 34 | } |
| 35 | |
| 36 | const WORKER_NAME = 'my-hello-world-worker'; |
| 37 | const SCRIPT_FILENAME = `${WORKER_NAME}.mjs`; |
| 38 | |
| 39 | function loadConfig(): Config { |
| 40 | const apiToken = process.env['CLOUDFLARE_API_TOKEN']; |
| 41 | if (!apiToken) { |
| 42 | throw new Error('Missing required environment variable: CLOUDFLARE_API_TOKEN'); |
| 43 | } |
| 44 | |
| 45 | const accountId = process.env['CLOUDFLARE_ACCOUNT_ID']; |
| 46 | if (!accountId) { |
| 47 | throw new Error('Missing required environment variable: CLOUDFLARE_ACCOUNT_ID'); |
| 48 | } |
| 49 | |
| 50 | const subdomain = process.env['CLOUDFLARE_SUBDOMAIN']; |
| 51 | |
| 52 | return { |
| 53 | apiToken, |
| 54 | accountId, |
| 55 | subdomain: subdomain || undefined, |
| 56 | workerName: WORKER_NAME, |
| 57 | }; |
| 58 | } |
| 59 | |
| 60 | const config = loadConfig(); |
| 61 | const client = new Cloudflare({ |
| 62 | apiToken: config.apiToken, |
| 63 | }); |
| 64 | |
| 65 | async function main(): Promise<void> { |
| 66 | try { |
| 67 | console.log('๐ Starting Worker creation and deployment...'); |
| 68 | |
| 69 | const scriptContent = ` |
| 70 | export default { |
| 71 | async fetch(request, env, ctx) { |
| 72 | return new Response(env.MESSAGE, { status: 200 }); |
| 73 | }, |
| 74 | }`.trim(); |
| 75 | |
| 76 | let worker; |
| 77 | try { |
| 78 | worker = await client.workers.beta.workers.get(config.workerName, { |
| 79 | account_id: config.accountId, |
| 80 | }); |
| 81 | console.log(`โป๏ธ Worker ${config.workerName} already exists. Using it.`); |
| 82 | } catch (error) { |
| 83 | if (!(error instanceof Cloudflare.NotFoundError)) { |
| 84 | throw error; |
| 85 | } |
| 86 | console.log(`โ๏ธ Creating Worker ${config.workerName}...`); |
| 87 | worker = await client.workers.beta.workers.create({ |
| 88 | account_id: config.accountId, |
| 89 | name: config.workerName, |
| 90 | subdomain: { |
| 91 | enabled: config.subdomain !== undefined, |
| 92 | }, |
| 93 | observability: { |
| 94 | enabled: true, |
| 95 | }, |
| 96 | }); |
| 97 | } |
| 98 | |
| 99 | console.log(`โ๏ธ Worker id: ${worker.id}`); |
| 100 | console.log('โ๏ธ Creating Worker version...'); |
| 101 | |
| 102 | // Create the first version of the Worker |
| 103 | const version = await client.workers.beta.workers.versions.create(worker.id, { |
| 104 | account_id: config.accountId, |
| 105 | main_module: SCRIPT_FILENAME, |
| 106 | compatibility_date: new Date().toISOString().split('T')[0]!, |
| 107 | bindings: [ |
| 108 | { |
| 109 | type: 'plain_text', |
| 110 | name: 'MESSAGE', |
| 111 | text: 'Hello World!', |
| 112 | }, |
| 113 | ], |
| 114 | modules: [ |
| 115 | { |
| 116 | name: SCRIPT_FILENAME, |
| 117 | content_type: 'application/javascript+module', |
| 118 | content_base64: Buffer.from(scriptContent).toString('base64'), |
| 119 | }, |
| 120 | ], |
| 121 | }); |
| 122 | |
| 123 | console.log(`โ๏ธ Version id: ${version.id}`); |
| 124 | console.log('๐ Creating Worker deployment...'); |
| 125 | |
| 126 | // Create a deployment and point all traffic to the version we created |
| 127 | await client.workers.scripts.deployments.create(config.workerName, { |
| 128 | account_id: config.accountId, |
| 129 | strategy: 'percentage', |
| 130 | versions: [ |
| 131 | { |
| 132 | percentage: 100, |
| 133 | version_id: version.id, |
| 134 | }, |
| 135 | ], |
| 136 | }); |
| 137 | |
| 138 | console.log('โ
Deployment successful!'); |
| 139 | |
| 140 | if (config.subdomain) { |
| 141 | console.log(` |
| 142 | ๐ Your Worker is live! |
| 143 | ๐ URL: https://${config.workerName}.${config.subdomain}.workers.dev/ |
| 144 | `); |
| 145 | } else { |
| 146 | console.log(` |
| 147 | โ ๏ธ Set up a route, custom domain, or workers.dev subdomain to access your Worker. |
| 148 | Add CLOUDFLARE_SUBDOMAIN to your environment variables to set one up automatically. |
| 149 | `); |
| 150 | } |
| 151 | } catch (error) { |
| 152 | console.error('โ Deployment failed:', error); |
| 153 | exit(1); |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | main(); |
| 158 | |