Skip to content

Commit ac82967

Browse files
committed
x
1 parent 22c26d1 commit ac82967

File tree

2 files changed

+68
-64
lines changed

2 files changed

+68
-64
lines changed

examples/workers/script-upload.ts

Lines changed: 48 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,39 @@
11
#!/usr/bin/env -S npm run tsn -T
22

3-
/*
4-
* Generate an API token: https://developers.cloudflare.com/fundamentals/api/get-started/create-token/
5-
* (Not Global API Key!)
3+
/**
4+
* Generate an API token:
5+
* https://developers.cloudflare.com/fundamentals/api/get-started/create-token/
6+
* (Not Global API Key!)
67
*
7-
* Find your account id: https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/
8+
* Find your account id:
9+
* https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/
810
*
911
* Set these environment variables:
10-
* - CLOUDFLARE_API_TOKEN
11-
* - CLOUDFLARE_ACCOUNT_ID
12-
*
13-
* ### Workers for Platforms ###
14-
*
15-
* For uploading a User Worker to a dispatch namespace:
16-
* https://developers.cloudflare.com/cloudflare-for-platforms/workers-for-platforms/
17-
*
18-
* Define a "dispatchNamespaceName" variable and change the entire "const script = " line to the following:
19-
* "const script = await client.workersForPlatforms.dispatch.namespaces.scripts.update(dispatchNamespaceName, scriptName, {"
12+
* - CLOUDFLARE_API_TOKEN
13+
* - CLOUDFLARE_ACCOUNT_ID
2014
*/
2115

2216
import Cloudflare from 'cloudflare';
23-
import { toFile } from 'cloudflare/index';
2417

2518
const apiToken = process.env['CLOUDFLARE_API_TOKEN'] ?? '';
2619
if (!apiToken) {
27-
throw new Error('Please set envar CLOUDFLARE_ACCOUNT_ID');
20+
throw new Error('Please set envar CLOUDFLARE_API_TOKEN');
2821
}
2922

3023
const accountID = process.env['CLOUDFLARE_ACCOUNT_ID'] ?? '';
3124
if (!accountID) {
32-
throw new Error('Please set envar CLOUDFLARE_API_TOKEN');
25+
throw new Error('Please set envar CLOUDFLARE_ACCOUNT_ID');
3326
}
3427

3528
const client = new Cloudflare({
36-
apiToken: apiToken,
29+
apiToken,
3730
});
3831

3932
async function main() {
40-
const scriptName = 'my-hello-world-script';
41-
const scriptFileName = `${scriptName}.mjs`;
33+
const workerName = 'my-hello-world-worker';
34+
const scriptFileName = `${workerName}.mjs`;
4235

43-
// Workers Scripts prefer Module Syntax
36+
// Workers Scripts use ES Module Syntax
4437
// https://blog.cloudflare.com/workers-javascript-modules/
4538
const scriptContent = `
4639
export default {
@@ -50,38 +43,42 @@ async function main() {
5043
};
5144
`;
5245

53-
try {
54-
// https://developers.cloudflare.com/api/resources/workers/subresources/scripts/methods/update/
55-
const script = await client.workers.scripts.update(scriptName, {
56-
account_id: accountID,
57-
// https://developers.cloudflare.com/workers/configuration/multipart-upload-metadata/
58-
metadata: {
59-
main_module: scriptFileName,
60-
bindings: [
61-
{
62-
type: 'plain_text',
63-
name: 'MESSAGE',
64-
text: 'Hello World!',
65-
},
66-
],
46+
const worker = await client.workers.create(workerName, {
47+
account_id: accountID,
48+
});
49+
50+
const version = await client.workers.scripts.create(worker.id, {
51+
account_id: accountID,
52+
main_module: scriptFileName,
53+
compatibility_date: new Date().toISOString().split('T')[0],
54+
bindings: [
55+
{
56+
type: 'plain_text',
57+
name: 'MESSAGE',
58+
text: 'Hello World!',
6759
},
68-
files: {
69-
// Add main_module file
70-
[scriptFileName]: await toFile(Buffer.from(scriptContent), scriptFileName, {
71-
type: 'application/javascript+module',
72-
}),
73-
// Can add other files, such as more modules or source maps
74-
// [sourceMapFileName]: await toFile(Buffer.from(sourceMapContent), sourceMapFileName, {
75-
// type: 'application/source-map',
76-
// }),
60+
],
61+
modules: [
62+
{
63+
name: scriptFileName,
64+
content_type: 'application/javascript+module',
65+
content_base64: Buffer.from(scriptContent).toString('base64'),
7766
},
78-
});
79-
console.log('Script Upload success!');
80-
console.log(JSON.stringify(script, null, 2));
81-
} catch (error) {
82-
console.error('Script Upload failure!');
83-
console.error(error);
84-
}
67+
],
68+
});
69+
70+
const deployment = await client.workers.scripts.deployments.create(worker.name, {
71+
account_id: accountID,
72+
strategy: 'percentage',
73+
versions: [
74+
{
75+
percentage: 100,
76+
version_id: version.id,
77+
},
78+
],
79+
});
80+
81+
console.log(JSON.stringify(deployment, null, 2));
8582
}
8683

8784
main();

examples/workers/script-with-assets-upload.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
#!/usr/bin/env -S npm run tsn -T
22

3-
/*
4-
* This is an example of how to upload a Worker with Static Assets and serve them from a Worker
3+
/**
4+
* Example: Upload a Worker with Static Assets and serve them from a Worker
55
* https://developers.cloudflare.com/workers/static-assets/direct-upload
66
*
7-
* Generate an API token: https://developers.cloudflare.com/fundamentals/api/get-started/create-token/
8-
* (Not Global API Key!)
7+
* Generate an API token:
8+
* https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ (Not Global API Key!)
99
*
10-
* Find your account id: https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/
10+
* Find your account id:
11+
* https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/
1112
*
1213
* Set these environment variables:
13-
* - CLOUDFLARE_API_TOKEN
14-
* - CLOUDFLARE_ACCOUNT_ID
15-
* - ASSETS_DIRECTORY
14+
* - CLOUDFLARE_API_TOKEN
15+
* - CLOUDFLARE_ACCOUNT_ID
16+
* - ASSETS_DIRECTORY
1617
*
17-
* In your assets directory, place files like html or images.
18+
* In your assets directory, place files like HTML or images.
1819
*
1920
* After deployment, your assets will be available at:
2021
* <worker-route>/<filename> (e.g. example.com/cat.jpg)
@@ -33,12 +34,12 @@ import { UploadCreateParams } from 'cloudflare/resources/workers/scripts/assets'
3334

3435
const apiToken = process.env['CLOUDFLARE_API_TOKEN'] ?? '';
3536
if (!apiToken) {
36-
throw new Error('Please set envar CLOUDFLARE_ACCOUNT_ID');
37+
throw new Error('Please set envar CLOUDFLARE_API_TOKEN');
3738
}
3839

3940
const accountID = process.env['CLOUDFLARE_ACCOUNT_ID'] ?? '';
4041
if (!accountID) {
41-
throw new Error('Please set envar CLOUDFLARE_API_TOKEN');
42+
throw new Error('Please set envar CLOUDFLARE_ACCOUNT_ID');
4243
}
4344

4445
const assetsDirectory = process.env['ASSETS_DIRECTORY'] ?? '';
@@ -47,7 +48,7 @@ if (!assetsDirectory) {
4748
}
4849

4950
const client = new Cloudflare({
50-
apiToken: apiToken,
51+
apiToken,
5152
});
5253

5354
/**
@@ -73,7 +74,7 @@ function createManifest(directory: string): Record<string, UploadCreateParams.Ma
7374
const fileContent = fs.readFileSync(fullPath);
7475
const extension = extname(relativePath).substring(1);
7576

76-
// Generate SHA-256 hash and encode in Base64
77+
// Generate hash and encode in Base64
7778
const hash = crypto
7879
.createHash('sha256')
7980
.update(fileContent.toString('base64') + extension)
@@ -104,6 +105,12 @@ async function main() {
104105
const scriptContent = `
105106
export default {
106107
async fetch(request, env, ctx) {
108+
if (request.url.pathname === '/') {
109+
return new Response(
110+
'Try going to /<filename> to serve an asset you uploaded!',
111+
{ status: 200 }
112+
);
113+
}
107114
return env.ASSETS.fetch(request);
108115
}
109116
};

0 commit comments

Comments
 (0)