From 2ea7189513ebb2c645686eb7f3d3d8fb148b63d6 Mon Sep 17 00:00:00 2001 From: Greg Brimble Date: Mon, 23 Sep 2024 02:30:28 -0400 Subject: [PATCH] Create C3 Frameworks component and rename Typescript to TypeScript --- .../code/AutomaticSpeechRecognitionCode.astro | 10 +- .../models/code/ImageClassificationCode.astro | 10 +- .../models/code/ImageToTextCode.astro | 7 +- .../models/code/ObjectDetectionCode.astro | 10 +- .../StableDiffusion-v1-5-img2imgCode.astro | 10 +- .../StableDiffusion-v1-5-inpaintingCode.astro | 10 +- .../models/code/SummarizationCode.astro | 10 +- .../models/code/TextClassificationCode.astro | 14 +- .../models/code/TextEmbeddingCode.astro | 31 +- .../models/code/TextToImageCode.astro | 10 +- .../models/code/TranslationCode.astro | 14 +- .../tutorials/deploy-aig-worker.mdx | 6 +- .../get-started/reuse-sessions.mdx | 6 +- .../get-started/screenshots.mdx | 6 +- .../get-started/configuration.mdx | 6 +- .../get-started/developing-with-wrangler.mdx | 18 +- .../identity/authorization-cookie/cors.mdx | 6 +- src/content/docs/d1/get-started.mdx | 274 ++++++++-------- .../tutorials/build-a-comments-api/index.mdx | 6 +- .../custom-access-control-for-files.mdx | 6 +- .../docs/durable-objects/get-started.mdx | 6 +- .../api/how-to/make-api-calls.mdx | 2 +- .../docs/fundamentals/api/reference/sdks.mdx | 23 +- .../basic-tasks/interact-with-cloudflare.mdx | 5 +- src/content/docs/hyperdrive/get-started.mdx | 6 +- .../index.mdx | 6 +- .../examples/workers-kv-to-serve-assets.mdx | 7 +- src/content/docs/kv/get-started.mdx | 215 +++++++------ .../workers/get-started/first-worker.mdx | 23 +- src/content/docs/queues/get-started.mdx | 6 +- .../index.mdx | 6 +- .../docs/r2/api/workers/workers-api-usage.mdx | 6 +- .../upload-logs-event-notifications.mdx | 6 +- .../docs/radar/investigate/bgp-anomalies.mdx | 6 +- .../docs/vectorize/get-started/embeddings.mdx | 6 +- .../docs/vectorize/get-started/intro.mdx | 6 +- .../get-started/workers-wrangler.mdx | 6 +- ...ld-a-retrieval-augmented-generation-ai.mdx | 37 ++- .../docs/workers/frameworks/get-started.mdx | 12 +- .../docs/workers/get-started/guide.mdx | 6 +- .../tutorials/build-a-jamstack-app/index.mdx | 6 +- .../build-a-qr-code-generator/index.mdx | 6 +- .../connect-to-turso-using-workers/index.mdx | 6 +- .../index.mdx | 6 +- .../index.mdx | 6 +- .../index.mdx | 6 +- .../index.mdx | 6 +- .../openai-function-calls-workers/index.mdx | 6 +- .../docs/workers/tutorials/postgres/index.mdx | 37 ++- .../tutorials/upload-assets-with-r2/index.mdx | 6 +- src/content/docs/workers/wrangler/api.mdx | 299 ++++++++---------- .../partials/workers/c3-post-run-steps.mdx | 30 +- src/content/partials/workers/source-maps.mdx | 3 +- 53 files changed, 644 insertions(+), 645 deletions(-) diff --git a/src/components/models/code/AutomaticSpeechRecognitionCode.astro b/src/components/models/code/AutomaticSpeechRecognitionCode.astro index 734acaaf6459cb..410a62ac1ca29d 100644 --- a/src/components/models/code/AutomaticSpeechRecognitionCode.astro +++ b/src/components/models/code/AutomaticSpeechRecognitionCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -36,7 +36,6 @@ export default { } satisfies ExportedHandler; `; - const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ -X POST \\ @@ -46,11 +45,10 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- diff --git a/src/components/models/code/ImageClassificationCode.astro b/src/components/models/code/ImageClassificationCode.astro index 21cb0d29a68712..91cd78e53c3fcc 100644 --- a/src/components/models/code/ImageClassificationCode.astro +++ b/src/components/models/code/ImageClassificationCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -34,7 +34,6 @@ export default { } satisfies ExportedHandler; `; - const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ -X POST \\ @@ -44,11 +43,10 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- diff --git a/src/components/models/code/ImageToTextCode.astro b/src/components/models/code/ImageToTextCode.astro index b7a3a11907d472..8b3b7fe7e13c3e 100644 --- a/src/components/models/code/ImageToTextCode.astro +++ b/src/components/models/code/ImageToTextCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -36,7 +36,6 @@ export default { ---

Code Examples

-
- +
+
- diff --git a/src/components/models/code/ObjectDetectionCode.astro b/src/components/models/code/ObjectDetectionCode.astro index be5244b891a4dd..2748abe8959f60 100644 --- a/src/components/models/code/ObjectDetectionCode.astro +++ b/src/components/models/code/ObjectDetectionCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -34,7 +34,6 @@ export default { } satisfies ExportedHandler; `; - const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ -X POST \\ @@ -44,11 +43,10 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- diff --git a/src/components/models/code/StableDiffusion-v1-5-img2imgCode.astro b/src/components/models/code/StableDiffusion-v1-5-img2imgCode.astro index 04d2fcaeef7793..ad0028c627736d 100644 --- a/src/components/models/code/StableDiffusion-v1-5-img2imgCode.astro +++ b/src/components/models/code/StableDiffusion-v1-5-img2imgCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -42,7 +42,6 @@ export default { } satisfies ExportedHandler; `; - const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ -X POST \\ @@ -52,11 +51,10 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- diff --git a/src/components/models/code/StableDiffusion-v1-5-inpaintingCode.astro b/src/components/models/code/StableDiffusion-v1-5-inpaintingCode.astro index 6b885aef995b7b..b865d3b2da2b01 100644 --- a/src/components/models/code/StableDiffusion-v1-5-inpaintingCode.astro +++ b/src/components/models/code/StableDiffusion-v1-5-inpaintingCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -49,7 +49,6 @@ export default { } satisfies ExportedHandler; `; - const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ -X POST \\ @@ -59,11 +58,10 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- diff --git a/src/components/models/code/SummarizationCode.astro b/src/components/models/code/SummarizationCode.astro index 7436e08bf6346b..061e5483378d86 100644 --- a/src/components/models/code/SummarizationCode.astro +++ b/src/components/models/code/SummarizationCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -26,7 +26,6 @@ export default { } satisfies ExportedHandler; `; - const curl = ` curl https://api.cloudflare.com/client/v4/accounts/{cf_account_id}/ai/run/${name} \\ -H "Authorization: Bearer {cf_api_token}" \\ @@ -38,11 +37,10 @@ curl https://api.cloudflare.com/client/v4/accounts/{cf_account_id}/ai/run/${name ---

Code Examples

-
- +
+
- +
- diff --git a/src/components/models/code/TextClassificationCode.astro b/src/components/models/code/TextClassificationCode.astro index 346f4a7ebcfe36..2928777ce3d405 100644 --- a/src/components/models/code/TextClassificationCode.astro +++ b/src/components/models/code/TextClassificationCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -40,8 +40,7 @@ def run(model, input): output = run("${name}", { "text": "This pizza is great!" }) print(output) -` - +`; const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ @@ -52,15 +51,14 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- +
- diff --git a/src/components/models/code/TextEmbeddingCode.astro b/src/components/models/code/TextEmbeddingCode.astro index 461ce09a4ba68e..98e5b9782ec777 100644 --- a/src/components/models/code/TextEmbeddingCode.astro +++ b/src/components/models/code/TextEmbeddingCode.astro @@ -5,7 +5,7 @@ import { Aside, Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -58,36 +58,35 @@ response = requests.post( ) print(response.json()) -` - +`; const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ -X POST \\ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \\ -d '{ "text": ["This is a story about an orange cloud", "This is a story about a llama", "This is a story about a hugging emoji"] }' -` +`; ---

Code Examples

-
- +
+
- +
- +
\ No newline at end of file + Workers AI also supports OpenAI compatible API endpoints for{" "} + /v1/chat/completions and /v1/embeddings. For more + details, refer to{" "} + + Configurations + + . + diff --git a/src/components/models/code/TextToImageCode.astro b/src/components/models/code/TextToImageCode.astro index 3c0f4a2213aba6..86cf6c76438a41 100644 --- a/src/components/models/code/TextToImageCode.astro +++ b/src/components/models/code/TextToImageCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -36,7 +36,6 @@ export default { } satisfies ExportedHandler; `; - const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ -X POST \\ @@ -46,11 +45,10 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- diff --git a/src/components/models/code/TranslationCode.astro b/src/components/models/code/TranslationCode.astro index cb3064b7d98d08..6ab6cc73b97db4 100644 --- a/src/components/models/code/TranslationCode.astro +++ b/src/components/models/code/TranslationCode.astro @@ -5,7 +5,7 @@ import { Code, Details } from "~/components"; type Props = z.infer; const props = z.object({ - name: z.string() + name: z.string(), }); const { name } = props.parse(Astro.props); @@ -49,8 +49,7 @@ output = run('${name}', { }) print(output) -` - +`; const curl = ` curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ @@ -61,15 +60,14 @@ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run ---

Code Examples

-
- +
+
- +
- +
- diff --git a/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx b/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx index f11306f50dbfdb..6022599fe79fd9 100644 --- a/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx +++ b/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx @@ -40,9 +40,9 @@ Create a Worker project in the command line: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/browser-rendering/get-started/reuse-sessions.mdx b/src/content/docs/browser-rendering/get-started/reuse-sessions.mdx index 1ff62a328345eb..20e6c786dcd00a 100644 --- a/src/content/docs/browser-rendering/get-started/reuse-sessions.mdx +++ b/src/content/docs/browser-rendering/get-started/reuse-sessions.mdx @@ -27,9 +27,9 @@ Create a new Worker project named `browser-worker` by running: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/browser-rendering/get-started/screenshots.mdx b/src/content/docs/browser-rendering/get-started/screenshots.mdx index 1bb9e8aac52857..d8cabbbeb5fa36 100644 --- a/src/content/docs/browser-rendering/get-started/screenshots.mdx +++ b/src/content/docs/browser-rendering/get-started/screenshots.mdx @@ -27,9 +27,9 @@ Create a new Worker project named `browser-worker` by running: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript / Typescript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript / TypeScript", }} /> diff --git a/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/configuration.mdx b/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/configuration.mdx index bec996b291e0bd..69d57d285da27d 100644 --- a/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/configuration.mdx +++ b/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/configuration.mdx @@ -85,9 +85,9 @@ Create your dispatch Worker. In this example, the dispatch Worker is called `my- file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/developing-with-wrangler.mdx b/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/developing-with-wrangler.mdx index c8f56e108e72db..c23084a172071d 100644 --- a/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/developing-with-wrangler.mdx +++ b/src/content/docs/cloudflare-for-platforms/workers-for-platforms/get-started/developing-with-wrangler.mdx @@ -26,9 +26,9 @@ Support for Workers for Platforms with `wrangler dev` in local mode is experimen file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> @@ -72,9 +72,9 @@ dispatch_namespace = "my-namespace" file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> @@ -128,9 +128,9 @@ outbound = { service = "outbound-worker", parameters = ["paramCustomerName"] } file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/cloudflare-one/identity/authorization-cookie/cors.mdx b/src/content/docs/cloudflare-one/identity/authorization-cookie/cors.mdx index e6897ce38cdc0e..ef3da21b79b745 100644 --- a/src/content/docs/cloudflare-one/identity/authorization-cookie/cors.mdx +++ b/src/content/docs/cloudflare-one/identity/authorization-cookie/cors.mdx @@ -157,9 +157,9 @@ This will prompt you to install the [`create-cloudflare`](https://www.npmjs.com/ file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/d1/get-started.mdx b/src/content/docs/d1/get-started.mdx index c7e29f2352c551..0084f2474d7677 100644 --- a/src/content/docs/d1/get-started.mdx +++ b/src/content/docs/d1/get-started.mdx @@ -20,8 +20,11 @@ To continue: 1. Sign up for a [Cloudflare account](https://dash.cloudflare.com/sign-up/workers-and-pages) if you have not already. + 2. Install [`npm`](https://docs.npmjs.com/getting-started). + 3. Install [`Node.js`](https://nodejs.org/en/). Use a Node version manager like [Volta](https://volta.sh/) or [nvm](https://github.com/nvm-sh/nvm) to avoid permission issues and change Node.js versions. [Wrangler](/workers/wrangler/install-and-update/) requires a Node version of `16.17.0` or later. + ## 1. Create a Worker @@ -31,38 +34,39 @@ Create a new Worker as the means to query your database. 1. Create a new project named `d1-tutorial` by running: - - - - - This creates a new `d1-tutorial` directory as illustrated below. - - - - d1-tutorial - - node_modules/ - - test/ - - src - - **index.ts** - - package-lock.json - - package.json - - testconfig.json - - vitest.config.mts - - worker-configuration.d.ts - - **wrangler.toml** - - - Your new `d1-tutorial` directory includes: - - - A `"Hello World"` [Worker](/workers/get-started/guide/#3-write-code) in `index.ts`. - - A [`wrangler.toml`](/workers/wrangler/configuration/) configuration file. `wrangler.toml` is how your `d1-tutorial` Worker accesses your D1 database. + + + + + This creates a new `d1-tutorial` directory as illustrated below. + + + - d1-tutorial + - node_modules/ + - test/ + - src + - **index.ts** + - package-lock.json + - package.json + - testconfig.json + - vitest.config.mts + - worker-configuration.d.ts + - **wrangler.toml** + + + Your new `d1-tutorial` directory includes: + + - A `"Hello World"` [Worker](/workers/get-started/guide/#3-write-code) in `index.ts`. + - A [`wrangler.toml`](/workers/wrangler/configuration/) configuration file. `wrangler.toml` is how your `d1-tutorial` Worker accesses your D1 database. + :::note @@ -82,25 +86,25 @@ To create your first D1 database: 1. Change into the directory you just created for your Workers project: - ```sh - cd d1-tutorial - ``` + ```sh + cd d1-tutorial + ``` 2. Run the following `wrangler d1` command and give your database a name. In this tutorial, the database is named `prod-d1-tutorial`: - ```sh - npx wrangler d1 create prod-d1-tutorial - ``` + ```sh + npx wrangler d1 create prod-d1-tutorial + ``` - ```sh output + ```sh output - βœ… Successfully created DB 'prod-d1-tutorial' + βœ… Successfully created DB 'prod-d1-tutorial' - [[d1_databases]] - binding = "DB" # available in your Worker on env.DB - database_name = "prod-d1-tutorial" - database_id = "" - ``` + [[d1_databases]] + binding = "DB" # available in your Worker on env.DB + database_name = "prod-d1-tutorial" + database_id = "" + ``` @@ -132,18 +136,18 @@ To bind your D1 database to your Worker: 1. Copy the lines obtained from [step 2](/d1/get-started/#2-create-a-database) from your terminal. 2. Add them to the end of your `wrangler.toml` file. - ```toml - [[d1_databases]] - binding = "DB" # available in your Worker on env.DB - database_name = "prod-d1-tutorial" - database_id = "" - ``` + ```toml + [[d1_databases]] + binding = "DB" # available in your Worker on env.DB + database_name = "prod-d1-tutorial" + database_id = "" + ``` - Specifically: + Specifically: - - The value (string) you set for `binding` is the **binding name**, and is used to reference this database in your Worker. In this tutorial, name your binding `DB`. - - The binding name must be [a valid JavaScript variable name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables). For example, `binding = "MY_DB"` or `binding = "productionDB"` would both be valid names for the binding. - - Your binding is available in your Worker at `env.` and the D1 [client API](/d1/build-with-d1/d1-client-api/) is exposed on this binding. + - The value (string) you set for `binding` is the **binding name**, and is used to reference this database in your Worker. In this tutorial, name your binding `DB`. + - The binding name must be [a valid JavaScript variable name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables). For example, `binding = "MY_DB"` or `binding = "productionDB"` would both be valid names for the binding. + - Your binding is available in your Worker at `env.` and the D1 [client API](/d1/build-with-d1/d1-client-api/) is exposed on this binding. @@ -164,39 +168,39 @@ With `wrangler.toml` configured properly, set up your database. Use the example 1. Copy the following code and save it as a `schema.sql` file in the `d1-tutorial` Worker directory you created in step 1: - ```sql - DROP TABLE IF EXISTS Customers; - CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT); - INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name'); - ``` + ```sql + DROP TABLE IF EXISTS Customers; + CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT); + INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name'); + ``` 2. Initialize your database to run and test locally first. Bootstrap your new D1 database by running: - ```sh - npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql - ``` + ```sh + npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql + ``` 3. Validate your data is in your database by running: - ```sh - npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT * FROM Customers" - ``` - - ```sh output - πŸŒ€ Mapping SQL input into an array of statements - πŸŒ€ Executing on local database production-db-backend (5f092302-3fbd-4247-a873-bf1afc5150b) from .wrangler/state/v3/d1: - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β”‚ CustomerId β”‚ CompanyName β”‚ ContactName β”‚ - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ 1 β”‚ Alfreds Futterkiste β”‚ Maria Anders β”‚ - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ 4 β”‚ Around the Horn β”‚ Thomas Hardy β”‚ - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ 11 β”‚ Bs Beverages β”‚ Victoria Ashworth β”‚ - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ 13 β”‚ Bs Beverages β”‚ Random Name β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - ``` + ```sh + npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT * FROM Customers" + ``` + + ```sh output + πŸŒ€ Mapping SQL input into an array of statements + πŸŒ€ Executing on local database production-db-backend (5f092302-3fbd-4247-a873-bf1afc5150b) from .wrangler/state/v3/d1: + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ CustomerId β”‚ CompanyName β”‚ ContactName β”‚ + β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ 1 β”‚ Alfreds Futterkiste β”‚ Maria Anders β”‚ + β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ 4 β”‚ Around the Horn β”‚ Thomas Hardy β”‚ + β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ 11 β”‚ Bs Beverages β”‚ Victoria Ashworth β”‚ + β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ 13 β”‚ Bs Beverages β”‚ Random Name β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ``` @@ -209,41 +213,41 @@ After you have set up your database, run an SQL query from within your Worker. 2. Clear the content of `index.ts`. 3. Paste the following code snippet into your `index.ts` file: - ```typescript - export interface Env { - // If you set another name in wrangler.toml as the value for 'binding', - // replace "DB" with the variable name you defined. - DB: D1Database; - } - - export default { - async fetch(request, env): Promise { - const { pathname } = new URL(request.url); - - if (pathname === "/api/beverages") { - // If you did not use `DB` as your binding name, change it here - const { results } = await env.DB.prepare( - "SELECT * FROM Customers WHERE CompanyName = ?", - ) - .bind("Bs Beverages") - .all(); - return Response.json(results); - } - - return new Response( - "Call /api/beverages to see everyone who works at Bs Beverages", - ); - }, - } satisfies ExportedHandler; - ``` - - In the code above, you: - - 1. Define a binding to your D1 database in your TypeScript code. This binding matches the `binding` value you set in `wrangler.toml` under `[[d1_databases]]`. - 2. Query your database using `env.DB.prepare` to issue a [prepared query](/d1/build-with-d1/d1-client-api/) with a placeholder (the `?` in the query). - 3. Call `bind()` to safely and securely bind a value to that placeholder. In a real application, you would allow a user to define the `CompanyName` they want to list results for. Using `bind()` prevents users from executing arbitrary SQL (known as "SQL injection") against your application and deleting or otherwise modifying your database. - 4. Execute the query by calling `all()` to return all rows (or none, if the query returns none). - 5. Return your query results, if any, in JSON format with `Response.json(results)`. + ```typescript + export interface Env { + // If you set another name in wrangler.toml as the value for 'binding', + // replace "DB" with the variable name you defined. + DB: D1Database; + } + + export default { + async fetch(request, env): Promise { + const { pathname } = new URL(request.url); + + if (pathname === "/api/beverages") { + // If you did not use `DB` as your binding name, change it here + const { results } = await env.DB.prepare( + "SELECT * FROM Customers WHERE CompanyName = ?", + ) + .bind("Bs Beverages") + .all(); + return Response.json(results); + } + + return new Response( + "Call /api/beverages to see everyone who works at Bs Beverages", + ); + }, + } satisfies ExportedHandler; + ``` + + In the code above, you: + + 1. Define a binding to your D1 database in your TypeScript code. This binding matches the `binding` value you set in `wrangler.toml` under `[[d1_databases]]`. + 2. Query your database using `env.DB.prepare` to issue a [prepared query](/d1/build-with-d1/d1-client-api/) with a placeholder (the `?` in the query). + 3. Call `bind()` to safely and securely bind a value to that placeholder. In a real application, you would allow a user to define the `CompanyName` they want to list results for. Using `bind()` prevents users from executing arbitrary SQL (known as "SQL injection") against your application and deleting or otherwise modifying your database. + 4. Execute the query by calling `all()` to return all rows (or none, if the query returns none). + 5. Return your query results, if any, in JSON format with `Response.json(results)`. @@ -256,17 +260,18 @@ While in your project directory, test your database locally. 1. Run `wrangler dev`: - ```sh - npx wrangler dev - ``` + ```sh + npx wrangler dev + ``` - When you run `wrangler dev`, Wrangler provides a URL (most likely `localhost:8787`) to review your Worker. + When you run `wrangler dev`, Wrangler provides a URL (most likely `localhost:8787`) to review your Worker. 2. Navigate to the URL. - The page displays `Call /api/beverages to see everyone who works at Bs Beverages`. + The page displays `Call /api/beverages to see everyone who works at Bs Beverages`. 3. Test your database is running successfully. Add `/api/beverages` to the provided Wrangler URL. For example, `localhost:8787/api/beverages`. + If successful, the browser displays your data. @@ -278,25 +283,26 @@ To deploy your Worker to production, you must first repeat the [database bootstr 1. Bootstrap your database with the `schema.sql` file you created in step 4: - ```sh - npx wrangler d1 execute prod-d1-tutorial --remote --file=./schema.sql - ``` + ```sh + npx wrangler d1 execute prod-d1-tutorial --remote --file=./schema.sql + ``` 2. Validate the data is in production by running: - ```sh - npx wrangler d1 execute prod-d1-tutorial --remote --command="SELECT * FROM Customers" - ``` + ```sh + npx wrangler d1 execute prod-d1-tutorial --remote --command="SELECT * FROM Customers" + ``` 3. Deploy your Worker to make your project accessible on the Internet. Run: - ```sh - npx wrangler deploy - ``` + ```sh + npx wrangler deploy + ``` + + ```sh output + Outputs: https://d1-tutorial..workers.dev + ``` - ```sh output - Outputs: https://d1-tutorial..workers.dev - ``` You can now visit the URL for your newly created project to query your live database. diff --git a/src/content/docs/d1/tutorials/build-a-comments-api/index.mdx b/src/content/docs/d1/tutorials/build-a-comments-api/index.mdx index 0d1d78bd3f81b6..c990438696f2d0 100644 --- a/src/content/docs/d1/tutorials/build-a-comments-api/index.mdx +++ b/src/content/docs/d1/tutorials/build-a-comments-api/index.mdx @@ -27,9 +27,9 @@ Use [C3](https://developers.cloudflare.com/learning-paths/workers/get-started/c3 file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/developer-spotlight/tutorials/custom-access-control-for-files.mdx b/src/content/docs/developer-spotlight/tutorials/custom-access-control-for-files.mdx index ab49e5932bc85d..ea115af2be033c 100644 --- a/src/content/docs/developer-spotlight/tutorials/custom-access-control-for-files.mdx +++ b/src/content/docs/developer-spotlight/tutorials/custom-access-control-for-files.mdx @@ -41,9 +41,9 @@ To get started developing your Worker you will use the [`create-cloudflare` CLI] file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/durable-objects/get-started.mdx b/src/content/docs/durable-objects/get-started.mdx index e32c8b15a32972..8746f9f4df8564 100644 --- a/src/content/docs/durable-objects/get-started.mdx +++ b/src/content/docs/durable-objects/get-started.mdx @@ -41,9 +41,9 @@ Running `create cloudflare@latest` will install [Wrangler](/workers/wrangler/ins file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker Using Durable Objects", - three: "JavaScript / Typescript", + category: "hello-world", + type: "Hello World Worker using Durable Objects", + lang: "JavaScript / TypeScript", }} /> diff --git a/src/content/docs/fundamentals/api/how-to/make-api-calls.mdx b/src/content/docs/fundamentals/api/how-to/make-api-calls.mdx index 6ab0a92073f614..a68b8d1ee71721 100644 --- a/src/content/docs/fundamentals/api/how-to/make-api-calls.mdx +++ b/src/content/docs/fundamentals/api/how-to/make-api-calls.mdx @@ -33,7 +33,7 @@ For specific guidance on making API calls, refer to the following resources: - The product's [Developer Docs section](/products/) for how-to guides. - [API schema docs](/api/) for request and response payloads for each endpoint. -- The first-party libraries for [Go](https://github.com/cloudflare/cloudflare-go), [Typescript](https://github.com/cloudflare/cloudflare-typescript), [Python](https://github.com/cloudflare/cloudflare-python), or [Hashicorp's Terraform](https://github.com/cloudflare/terraform-provider-cloudflare). +- The first-party libraries for [Go](https://github.com/cloudflare/cloudflare-go), [TypeScript](https://github.com/cloudflare/cloudflare-typescript), [Python](https://github.com/cloudflare/cloudflare-python), or [Hashicorp's Terraform](https://github.com/cloudflare/terraform-provider-cloudflare). ## Query parameters diff --git a/src/content/docs/fundamentals/api/reference/sdks.mdx b/src/content/docs/fundamentals/api/reference/sdks.mdx index 79402d73f42f70..acb8ebfda6a950 100644 --- a/src/content/docs/fundamentals/api/reference/sdks.mdx +++ b/src/content/docs/fundamentals/api/reference/sdks.mdx @@ -3,27 +3,26 @@ pcx_content_type: reference title: SDKs sidebar: order: 5 - --- Cloudflare offers language software development kits (SDKs) as well as `curl` examples to demonstrate how to use the Cloudflare API. The SDK libraries allow you to interact with the Cloudflare API in language-specific syntax and more easily integrate with your existing applications. Cloudflare currently offers the following SDKs: -* [Go](https://github.com/cloudflare/cloudflare-go) -* [Typescript](https://github.com/cloudflare/cloudflare-typescript) -* [Python](https://github.com/cloudflare/cloudflare-python) +- [Go](https://github.com/cloudflare/cloudflare-go) +- [TypeScript](https://github.com/cloudflare/cloudflare-typescript) +- [Python](https://github.com/cloudflare/cloudflare-python) ## When to use cURL vs SDK There is no definite answer on which you should use. Instead, consider your use case and determine whether cURL or an SDK is the best fit. -| Use case | cURL | SDK | -| ----------------------------------------------------------- | ---- | --- | -| Quick testing within the CLI | βœ… | ❌ | -| Use within bash scripts or CI | βœ… | ❌\* | -| Usage from within an existing application or framework | ❌ | βœ… | -| More complex usage where you need to chain together outputs | ❌ | βœ… | +| Use case | cURL | SDK | +| ----------------------------------------------------------- | ---- | ---- | +| Quick testing within the CLI | βœ… | ❌ | +| Use within bash scripts or CI | βœ… | ❌\* | +| Usage from within an existing application or framework | ❌ | βœ… | +| More complex usage where you need to chain together outputs | ❌ | βœ… | \* It is possible, although not straight forward, to use the SDKs within bash scripts or CI environments with additional runtime dependencies and setup. @@ -38,11 +37,11 @@ curl "https://api.cloudflare.com/client/v4/zones" \ --header "Authorization: Bearer " ``` -### With the Typescript SDK: +### With the TypeScript SDK: ```js const client = new Cloudflare({ - apiToken: process.env["CLOUDFLARE_API_TOKEN"], + apiToken: process.env["CLOUDFLARE_API_TOKEN"], }); const zones = await client.zones.list(); diff --git a/src/content/docs/fundamentals/basic-tasks/interact-with-cloudflare.mdx b/src/content/docs/fundamentals/basic-tasks/interact-with-cloudflare.mdx index 0b24d5fd33edc5..de17c14c011c99 100644 --- a/src/content/docs/fundamentals/basic-tasks/interact-with-cloudflare.mdx +++ b/src/content/docs/fundamentals/basic-tasks/interact-with-cloudflare.mdx @@ -1,7 +1,6 @@ --- pcx_content_type: concept title: Interacting with Cloudflare - --- Once you [set up an account](/fundamentals/setup/account/), you have several ways to interact with Cloudflare. @@ -12,10 +11,8 @@ If you prefer working without code, you can manage your account and domain setti :::note - If your domain was added to Cloudflare by a hosting partner, manage your DNS records via the hosting partner. - ::: ## With code @@ -27,5 +24,5 @@ For those who prefer to interact with Cloudflare programmatically, you can use s | [Cloudflare API](/fundamentals/api/) | [API docs](/api/) | RESTful API based on HTTPS requests and JSON responses. | | [Terraform](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs) | [Terraform docs](/terraform/) | Configure Cloudflare using HashiCorp’s Infrastructure as Code tool, Terraform. | | [cloudflare-go](https://github.com/cloudflare/cloudflare-go) | [README](https://github.com/cloudflare/cloudflare-go#readme) | The official Go library for the Cloudflare API. | -| [cloudflare-typescript](https://github.com/cloudflare/cloudflare-typescript) | [README](https://github.com/cloudflare/cloudflare-typescript#readme) | The official Typescript library for the Cloudflare API. | +| [cloudflare-typescript](https://github.com/cloudflare/cloudflare-typescript) | [README](https://github.com/cloudflare/cloudflare-typescript#readme) | The official TypeScript library for the Cloudflare API. | | [cloudflare-python](https://github.com/cloudflare/cloudflare-python) | [README](https://github.com/cloudflare/cloudflare-python#readme) | The official Python library for the Cloudflare API. | diff --git a/src/content/docs/hyperdrive/get-started.mdx b/src/content/docs/hyperdrive/get-started.mdx index 6d71449e35be1e..b3500aebffbbd0 100644 --- a/src/content/docs/hyperdrive/get-started.mdx +++ b/src/content/docs/hyperdrive/get-started.mdx @@ -64,9 +64,9 @@ Create a new project named `hyperdrive-tutorial` by running: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/hyperdrive/tutorials/serverless-timeseries-api-with-timescale/index.mdx b/src/content/docs/hyperdrive/tutorials/serverless-timeseries-api-with-timescale/index.mdx index cc4c8dc5b647b2..3238d69e02d909 100644 --- a/src/content/docs/hyperdrive/tutorials/serverless-timeseries-api-with-timescale/index.mdx +++ b/src/content/docs/hyperdrive/tutorials/serverless-timeseries-api-with-timescale/index.mdx @@ -41,9 +41,9 @@ Run the following command to create a Worker project from the command line: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/kv/examples/workers-kv-to-serve-assets.mdx b/src/content/docs/kv/examples/workers-kv-to-serve-assets.mdx index e90f9deca9dd3e..39ad96b52e08c0 100644 --- a/src/content/docs/kv/examples/workers-kv-to-serve-assets.mdx +++ b/src/content/docs/kv/examples/workers-kv-to-serve-assets.mdx @@ -10,7 +10,6 @@ sidebar: description: Example of how to use Workers KV to store static assets --- - import { Render, PackageManagers } from "~/components"; By storing static assets in Workers KV, you can retrieve these assets globally with low-latency and high throughput. You can then serve these assets directly, or use them to dynamically generate responses. This can be useful when serving files and images, or when generating dynamic HTML responses from static assets such as translations. @@ -35,9 +34,9 @@ To get started, create a Worker application using the [`create-cloudflare` CLI]( file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/kv/get-started.mdx b/src/content/docs/kv/get-started.mdx index 0c17f4cd9b6e1a..5964dc3f90dfa2 100644 --- a/src/content/docs/kv/get-started.mdx +++ b/src/content/docs/kv/get-started.mdx @@ -5,7 +5,13 @@ sidebar: order: 2 --- -import { Render, PackageManagers, Steps, FileTree, Details } from "~/components"; +import { + Render, + PackageManagers, + Steps, + FileTree, + Details, +} from "~/components"; Workers KV provides low-latency, high-throughput global storage to your [Cloudflare Workers](/workers/) applications. Workers KV is ideal for storing user configuration data, routing data, A/B testing configurations and authentication tokens, and is well suited for read-heavy workloads. @@ -21,9 +27,13 @@ To continue: 1. Sign up for a [Cloudflare account](https://dash.cloudflare.com/sign-up/workers-and-pages) if you have not already. + 2. Install [`npm`](https://docs.npmjs.com/getting-started). + 3. Install [`Node.js`](https://nodejs.org/en/). Use a Node version manager like [Volta](https://volta.sh/) or [nvm](https://github.com/nvm-sh/nvm) to avoid permission issues and change Node.js versions. [Wrangler](/workers/wrangler/install-and-update/) requires a Node version of `16.13.0` or later. + 4. Update your [Wrangler](/workers/wrangler/install-and-update/) installation to the most updated version. + ## 1. Create a Worker project @@ -39,44 +49,45 @@ Create a new Worker to read and write to your KV namespace. 1. Create a new project named `kv-tutorial` by running: - - - - - This creates a new `kv-tutorial` directory, illustrated below. - - - - kv-tutorial/ - - node_modules/ - - test/ - - src - - **index.ts** - - package-lock.json - - package.json - - testconfig.json - - vitest.config.mts - - worker-configuration.d.ts - - **wrangler.toml** - - - Your new `kv-tutorial` directory includes: - - - A `"Hello World"` [Worker](/workers/get-started/guide/#3-write-code) in `index.ts`. - - A [`wrangler.toml`](/workers/wrangler/configuration/) configuration file. `wrangler.toml` is how your `kv-tutorial` Worker accesses your kv database. + + + + + This creates a new `kv-tutorial` directory, illustrated below. + + + - kv-tutorial/ + - node_modules/ + - test/ + - src + - **index.ts** + - package-lock.json + - package.json + - testconfig.json + - vitest.config.mts + - worker-configuration.d.ts + - **wrangler.toml** + + + Your new `kv-tutorial` directory includes: + + - A `"Hello World"` [Worker](/workers/get-started/guide/#3-write-code) in `index.ts`. + - A [`wrangler.toml`](/workers/wrangler/configuration/) configuration file. `wrangler.toml` is how your `kv-tutorial` Worker accesses your kv database. 2. Change into the directory you just created for your Worker project: - ```sh - cd kv-tutorial - ``` + ```sh + cd kv-tutorial + ``` + :::note @@ -107,38 +118,39 @@ To create a KV namespace via Wrangler: 1. Open your terminal and run the following command: - ```sh - npx wrangler kv namespace create - ``` + ```sh + npx wrangler kv namespace create + ``` - The `npx wrangler kv namespace create ` subcommand takes a new binding name as its argument. A KV namespace is created using a concatenation of your Worker’s name (from your `wrangler.toml` file) and the binding name you provide. The `id` is randomly generated for you. + The `npx wrangler kv namespace create ` subcommand takes a new binding name as its argument. A KV namespace is created using a concatenation of your Worker’s name (from your `wrangler.toml` file) and the binding name you provide. The `id` is randomly generated for you. - ```sh - npx wrangler kv namespace create - ``` + ```sh + npx wrangler kv namespace create + ``` - ```sh output - πŸŒ€ Creating namespace with title - ✨ Success! - Add the following to your configuration file: - kv_namespaces = [ - { binding = , id = "e29b263ab50e42ce9b637fa8370175e8" } - ] - ``` + ```sh output + πŸŒ€ Creating namespace with title + ✨ Success! + Add the following to your configuration file: + kv_namespaces = [ + { binding = , id = "e29b263ab50e42ce9b637fa8370175e8" } + ] + ``` 2. In your `wrangler.toml` file, add the following with the values generated in your terminal: - ```toml - kv_namespaces = [ - { binding = "", id = "" } - ] - ``` + ```toml + kv_namespaces = [ + { binding = "", id = "" } + ] + ``` + + Binding names do not need to correspond to the namespace you created. Binding names are only a reference. Specifically: - Binding names do not need to correspond to the namespace you created. Binding names are only a reference. Specifically: + - The value (string) you set for `` is used to reference this database in your Worker. In this tutorial, name your binding `DB`. + - The binding must be [a valid JavaScript variable name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables). For example, `binding = "MY_KV"` or `binding = "routingConfig"` would both be valid names for the binding. + - Your binding is available in your Worker at `env.` from within your Worker. - - The value (string) you set for `` is used to reference this database in your Worker. In this tutorial, name your binding `DB`. - - The binding must be [a valid JavaScript variable name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables). For example, `binding = "MY_KV"` or `binding = "routingConfig"` would both be valid names for the binding. - - Your binding is available in your Worker at `env.` from within your Worker. :::note[Bindings] @@ -153,10 +165,15 @@ Refer to [Environment](/kv/reference/environments/) for more information. 1. Log in to the [Cloudflare dashboard](https://dash.cloudflare.com). + 2. Select **Workers & Pages** > **KV**. + 3. Select **Create a namespace**. + 4. Enter a name for your namespace. + 5. Select **Add**. + :::note @@ -175,13 +192,14 @@ To write a value to your empty KV namespace using Wrangler: 1. Run the `wrangler kv key put` subcommand in your terminal, and input your key and value respectively. `` and `` are values of your choice. - ```sh - npx wrangler kv key put --binding= "" "" - ``` + ```sh + npx wrangler kv key put --binding= "" "" + ``` + + ```sh output + Writing the value "" to key "" on namespace e29b263ab50e42ce9b637fa8370175e8. + ``` - ```sh output - Writing the value "" to key "" on namespace e29b263ab50e42ce9b637fa8370175e8. - ``` Instead of using `--binding`, you can also use `--namespace-id` to specify which KV namespace should receive the operation: @@ -207,27 +225,28 @@ To access the value using Wrangler: 1. Run the `wrangler kv key get` subcommand in your terminal, and input your key value: - ```sh - # Replace [OPTIONS] with --binding or --namespace-id - npx wrangler kv key get [OPTIONS] "" - ``` + ```sh + # Replace [OPTIONS] with --binding or --namespace-id + npx wrangler kv key get [OPTIONS] "" + ``` - A KV namespace can be specified in two ways: + A KV namespace can be specified in two ways: -
+
- ```sh - npx wrangler kv key get --binding= "" - ``` + ```sh + npx wrangler kv key get --binding= "" + ``` -
+
-
+
+ + ```sh + npx wrangler kv key get --namespace-id= "" + ``` +
- ```sh - npx wrangler kv key get --namespace-id= "" - ``` -
You can add a `--preview` flag to interact with a preview namespace instead of a production namespace. @@ -258,24 +277,25 @@ To have `wrangler dev` connect to your Workers KV namespace running on Cloudflar 1. In your Worker script, add your KV namespace in the `Env` interface: - ```ts - interface Env { - YOUR_KV_NAMESPACE: KVNamespace; - // ... other binding types - } - ``` + ```ts + interface Env { + YOUR_KV_NAMESPACE: KVNamespace; + // ... other binding types + } + ``` 2. Use the `put()` method on `YOUR_KV_NAMESPACE` to create a new key-value pair, or to update the value for a particular key: - ```ts - let value = await env.YOUR_KV_NAMESPACE.put(key, value); - ``` + ```ts + let value = await env.YOUR_KV_NAMESPACE.put(key, value); + ``` 3. Use the KV `get()` method to fetch the data you stored in your KV database: - ```ts - let value = await env.YOUR_KV_NAMESPACE.get("KEY"); - ``` + ```ts + let value = await env.YOUR_KV_NAMESPACE.get("KEY"); + ``` + Your Worker code should look like this: @@ -323,13 +343,14 @@ When you run `wrangler dev`, Wrangler provides a URL (usually a `localhost:8787` 1. Run the following command to deploy KV to Cloudflare's global network: - ```sh - npx wrangler deploy - ``` + ```sh + npx wrangler deploy + ``` 2. Visit the URL for your newly created Workers KV application. - For example, if the URL of your new Worker is `kv-tutorial..workers.dev`, accessing `https://kv-tutorial..workers.dev/` sends a request to your Worker that writes (and reads) from Workers KV. + For example, if the URL of your new Worker is `kv-tutorial..workers.dev`, accessing `https://kv-tutorial..workers.dev/` sends a request to your Worker that writes (and reads) from Workers KV. + ## Summary diff --git a/src/content/docs/learning-paths/workers/get-started/first-worker.mdx b/src/content/docs/learning-paths/workers/get-started/first-worker.mdx index aa84d8a2fc6e66..28b69e3c3c103a 100644 --- a/src/content/docs/learning-paths/workers/get-started/first-worker.mdx +++ b/src/content/docs/learning-paths/workers/get-started/first-worker.mdx @@ -3,10 +3,9 @@ title: First Worker pcx_content_type: learning-unit sidebar: order: 2 - --- -import { Render, PackageManagers } from "~/components" +import { Render, PackageManagers } from "~/components"; ## Build and deploy your first Worker @@ -30,17 +29,25 @@ You must have a Cloudflare account to create a Worker. To get started with Cloud To create your Worker project, run: - + This will prompt you to install the [`create-cloudflare`](https://www.npmjs.com/package/create-cloudflare) package, and lead you through setup. - + You will be asked if you would like to deploy the project to Cloudflare. -* If you choose to deploy, you will be asked to authenticate (if not logged in already), and your project will be deployed to the Cloudflare global network and available on your custom [`workers.dev` subdomain](/workers/configuration/routing/workers-dev/). +- If you choose to deploy, you will be asked to authenticate (if not logged in already), and your project will be deployed to the Cloudflare global network and available on your custom [`workers.dev` subdomain](/workers/configuration/routing/workers-dev/). -* If you choose not to deploy, go to the newly created project directory to begin writing code. Deploy your project by running the [`wrangler deploy`](/workers/wrangler/commands/#deploy) command. +- If you choose not to deploy, go to the newly created project directory to begin writing code. Deploy your project by running the [`wrangler deploy`](/workers/wrangler/commands/#deploy) command. Refer to [How to run Wrangler commands](/workers/wrangler/commands/#how-to-run-wrangler-commands) to learn how to run Wrangler commands according to your package manager. @@ -58,10 +65,10 @@ To continue building your Worker, open the `index.js` file to write your code. R You have learned how to: -* Create and deploy a Worker project using the Cloudflare dashboard and programmatically, using your terminal. +- Create and deploy a Worker project using the Cloudflare dashboard and programmatically, using your terminal. In the next section, you can follow a video tutorial to create your first Cloudflare Workers application. ### Related resources -* [Get started guide](/workers/get-started/guide/) - Create a new Worker with Cloudflare Workers' Get started guide. +- [Get started guide](/workers/get-started/guide/) - Create a new Worker with Cloudflare Workers' Get started guide. diff --git a/src/content/docs/queues/get-started.mdx b/src/content/docs/queues/get-started.mdx index c10bd529175999..462b0185069e24 100644 --- a/src/content/docs/queues/get-started.mdx +++ b/src/content/docs/queues/get-started.mdx @@ -38,9 +38,9 @@ To create a producer Worker, run: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/queues/tutorials/web-crawler-with-browser-rendering/index.mdx b/src/content/docs/queues/tutorials/web-crawler-with-browser-rendering/index.mdx index 17fc455b100d2c..38c431f7de9d31 100644 --- a/src/content/docs/queues/tutorials/web-crawler-with-browser-rendering/index.mdx +++ b/src/content/docs/queues/tutorials/web-crawler-with-browser-rendering/index.mdx @@ -51,9 +51,9 @@ To get started, create a Worker application using the [`create-cloudflare` CLI]( file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/r2/api/workers/workers-api-usage.mdx b/src/content/docs/r2/api/workers/workers-api-usage.mdx index 1374d126445d48..f817b60b47ed38 100644 --- a/src/content/docs/r2/api/workers/workers-api-usage.mdx +++ b/src/content/docs/r2/api/workers/workers-api-usage.mdx @@ -22,9 +22,9 @@ To get started, open a terminal window and run: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/r2/examples/upload-logs-event-notifications.mdx b/src/content/docs/r2/examples/upload-logs-event-notifications.mdx index d4ddfe71a64b7c..ca50f8c2e55ded 100644 --- a/src/content/docs/r2/examples/upload-logs-event-notifications.mdx +++ b/src/content/docs/r2/examples/upload-logs-event-notifications.mdx @@ -69,9 +69,9 @@ Create a new Worker with C3 (`create-cloudflare` CLI). [C3](/pages/get-started/c file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/radar/investigate/bgp-anomalies.mdx b/src/content/docs/radar/investigate/bgp-anomalies.mdx index 3148040a4c8859..279344513f232d 100644 --- a/src/content/docs/radar/investigate/bgp-anomalies.mdx +++ b/src/content/docs/radar/investigate/bgp-anomalies.mdx @@ -186,9 +186,9 @@ First, create a new Workers app in a local directory: file="c3-post-run-steps" product="workers" params={{ - one: "Demo application", - two: "Scheduled Worker (Cron Trigger)", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/vectorize/get-started/embeddings.mdx b/src/content/docs/vectorize/get-started/embeddings.mdx index e1d692191a8f13..59c9e64127144b 100644 --- a/src/content/docs/vectorize/get-started/embeddings.mdx +++ b/src/content/docs/vectorize/get-started/embeddings.mdx @@ -48,9 +48,9 @@ Open your terminal and create a new project named `embeddings-tutorial` by runni file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/vectorize/get-started/intro.mdx b/src/content/docs/vectorize/get-started/intro.mdx index 30161fb2533757..c9dd050e36a8a6 100644 --- a/src/content/docs/vectorize/get-started/intro.mdx +++ b/src/content/docs/vectorize/get-started/intro.mdx @@ -53,9 +53,9 @@ Create a new project named `vectorize-tutorial` by running: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/workers-ai/get-started/workers-wrangler.mdx b/src/content/docs/workers-ai/get-started/workers-wrangler.mdx index 057f95eed14f9d..9566085ddd6219 100644 --- a/src/content/docs/workers-ai/get-started/workers-wrangler.mdx +++ b/src/content/docs/workers-ai/get-started/workers-wrangler.mdx @@ -29,9 +29,9 @@ Running `npm create cloudflare@latest` will prompt you to install the [`create-c file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/workers-ai/tutorials/build-a-retrieval-augmented-generation-ai.mdx b/src/content/docs/workers-ai/tutorials/build-a-retrieval-augmented-generation-ai.mdx index 2000fb609ae945..18a72b26a62dd8 100644 --- a/src/content/docs/workers-ai/tutorials/build-a-retrieval-augmented-generation-ai.mdx +++ b/src/content/docs/workers-ai/tutorials/build-a-retrieval-augmented-generation-ai.mdx @@ -42,9 +42,9 @@ Open a terminal window and run C3 to create your Worker project: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> @@ -265,8 +265,7 @@ By doing this, you will create a new vector representation of the note, which ca To complete your code, you can update the root path (`/`) to query Vectorize. You will convert the query into a vector, and then use the `vector-index` index to find the most similar vectors. -The `topK` parameter limits the number of vectors returned by the function. For instance, providing a `topK` of 1 will only return the *most similar* vector based on the query. Setting `topK` to 5 will return the 5 most similar vectors. - +The `topK` parameter limits the number of vectors returned by the function. For instance, providing a `topK` of 1 will only return the _most similar_ vector based on the query. Setting `topK` to 5 will return the 5 most similar vectors. Given a list of similar vectors, you can retrieve the notes that match the record IDs stored alongside those vectors. In this case, we are only retrieving a single note - but you may customize this as needed. @@ -350,16 +349,16 @@ export default app; If you no longer need a note, you can delete it from the database. Any time that you delete a note, you will also need to delete the corresponding vector from Vectorize. You can implement this by building a `DELETE /notes/:id` route in your `src/index.js` file: ```js -app.delete('/notes/:id', async (c) => { - const { id } = c.req.param(); +app.delete("/notes/:id", async (c) => { + const { id } = c.req.param(); - const query = `DELETE FROM notes WHERE id = ?` - await c.env.DATABASE.prepare(query).bind(id).run() + const query = `DELETE FROM notes WHERE id = ?`; + await c.env.DATABASE.prepare(query).bind(id).run(); - await c.env.VECTOR_INDEX.deleteByIds([id]) + await c.env.VECTOR_INDEX.deleteByIds([id]); - return c.status(204) -}) + return c.status(204); +}); ``` ## 8. Deploy your project @@ -384,10 +383,10 @@ A full version of this codebase is available on GitHub. It includes a frontend U To do more: -* Explore the reference diagram for a [Retrieval Augmented Generation (RAG) Architecture](/reference-architecture/diagrams/ai/ai-rag/). -* Review Cloudflare's [AI documentation](/workers-ai). -* Review [Tutorials](/workers/tutorials/) to build projects on Workers. -* Explore [Examples](/workers/examples/) to experiment with copy and paste Worker code. -* Understand how Workers works in [Reference](/workers/reference/). -* Learn about Workers features and functionality in [Platform](/workers/platform/). -* Set up [Wrangler](/workers/wrangler/install-and-update/) to programmatically create, test, and deploy your Worker projects. +- Explore the reference diagram for a [Retrieval Augmented Generation (RAG) Architecture](/reference-architecture/diagrams/ai/ai-rag/). +- Review Cloudflare's [AI documentation](/workers-ai). +- Review [Tutorials](/workers/tutorials/) to build projects on Workers. +- Explore [Examples](/workers/examples/) to experiment with copy and paste Worker code. +- Understand how Workers works in [Reference](/workers/reference/). +- Learn about Workers features and functionality in [Platform](/workers/platform/). +- Set up [Wrangler](/workers/wrangler/install-and-update/) to programmatically create, test, and deploy your Worker projects. diff --git a/src/content/docs/workers/frameworks/get-started.mdx b/src/content/docs/workers/frameworks/get-started.mdx index 38719411a90f18..94e2d8b16fa5d8 100644 --- a/src/content/docs/workers/frameworks/get-started.mdx +++ b/src/content/docs/workers/frameworks/get-started.mdx @@ -43,9 +43,9 @@ This guide will instruct you through setting up and deploying a static site on W file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World - Assets Only", - three: "TypeScript", + category: "hello-world", + type: "Hello World - Assets Only", + lang: "TypeScript", }} /> @@ -93,9 +93,9 @@ Open a terminal window and run C3 to create your Worker project: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker + Assets", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker + Assets", + lang: "TypeScript", }} /> diff --git a/src/content/docs/workers/get-started/guide.mdx b/src/content/docs/workers/get-started/guide.mdx index 75f3eec08392db..8a019fabfc9e1b 100644 --- a/src/content/docs/workers/get-started/guide.mdx +++ b/src/content/docs/workers/get-started/guide.mdx @@ -34,9 +34,9 @@ Open a terminal window and run C3 to create your Worker project: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx b/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx index 07f98eba98e8af..5cb3989db1e892 100644 --- a/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx +++ b/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx @@ -35,9 +35,9 @@ First, use the [`create-cloudflare`](https://www.npmjs.com/package/create-cloudf file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/workers/tutorials/build-a-qr-code-generator/index.mdx b/src/content/docs/workers/tutorials/build-a-qr-code-generator/index.mdx index ce975ee5e5c893..87c89ff7320cc1 100644 --- a/src/content/docs/workers/tutorials/build-a-qr-code-generator/index.mdx +++ b/src/content/docs/workers/tutorials/build-a-qr-code-generator/index.mdx @@ -30,9 +30,9 @@ First, use the [`create-cloudflare` CLI](/pages/get-started/c3) to create a new file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/workers/tutorials/connect-to-turso-using-workers/index.mdx b/src/content/docs/workers/tutorials/connect-to-turso-using-workers/index.mdx index 4db81b7ea7a63e..f961014764e68e 100644 --- a/src/content/docs/workers/tutorials/connect-to-turso-using-workers/index.mdx +++ b/src/content/docs/workers/tutorials/connect-to-turso-using-workers/index.mdx @@ -116,9 +116,9 @@ To create a new Workers project (named `worker-turso-ts`), run the following: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx b/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx index 208ae175b8e614..63c2ccafd444b0 100644 --- a/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx +++ b/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx @@ -53,9 +53,9 @@ First, use the `c3` CLI to create a new Cloudflare Workers project. file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/workers/tutorials/generate-youtube-thumbnails-with-workers-and-images/index.mdx b/src/content/docs/workers/tutorials/generate-youtube-thumbnails-with-workers-and-images/index.mdx index 58e2388219ddab..1493ef1b485b41 100644 --- a/src/content/docs/workers/tutorials/generate-youtube-thumbnails-with-workers-and-images/index.mdx +++ b/src/content/docs/workers/tutorials/generate-youtube-thumbnails-with-workers-and-images/index.mdx @@ -364,9 +364,9 @@ Create a Worker to serve the image you uploaded to Images by running: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx b/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx index bd031d6e0a589a..fa0f520a04bcb6 100644 --- a/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx +++ b/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx @@ -38,9 +38,9 @@ Start by using `npm create cloudflare@latest` to create a Worker project in the file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/workers/tutorials/handle-form-submissions-with-airtable/index.mdx b/src/content/docs/workers/tutorials/handle-form-submissions-with-airtable/index.mdx index bf882ad827819e..9417ea7597d24b 100644 --- a/src/content/docs/workers/tutorials/handle-form-submissions-with-airtable/index.mdx +++ b/src/content/docs/workers/tutorials/handle-form-submissions-with-airtable/index.mdx @@ -92,9 +92,9 @@ Create a new `airtable-form-handler` Worker project: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx b/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx index b3804c1f3342e6..c53c8e7cae2569 100644 --- a/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx +++ b/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx @@ -42,9 +42,9 @@ Create a Worker project in the command line: file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "JavaScript", + category: "hello-world", + type: "Hello World Worker", + lang: "JavaScript", }} /> diff --git a/src/content/docs/workers/tutorials/postgres/index.mdx b/src/content/docs/workers/tutorials/postgres/index.mdx index 3d57e42048c8c6..f29c3d782d84ad 100644 --- a/src/content/docs/workers/tutorials/postgres/index.mdx +++ b/src/content/docs/workers/tutorials/postgres/index.mdx @@ -42,9 +42,9 @@ This will prompt you to install the [`create-cloudflare`](https://www.npmjs.com/ file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> @@ -102,7 +102,7 @@ npx wrangler secret put DB_URL Set your `DB_URL` secret locally in a `.dev.vars` file as documented in [Local Development with Secrets](/workers/configuration/secrets/). -```toml +```toml DB_URL="" ``` @@ -136,7 +136,7 @@ npx wrangler secret put DB_PASSWORD Open your Worker's main file (for example, `worker.ts`) and import the `Client` class from the `pg` library: ```typescript -import postgres from 'postgres' +import postgres from "postgres"; ``` In the `fetch` event handler, connect to the PostgreSQL database using your chosen method, either the connection string or the explicit parameters. @@ -144,7 +144,7 @@ In the `fetch` event handler, connect to the PostgreSQL database using your chos ### Use a connection string ```typescript -const sql = postgres(env.DB_URL) +const sql = postgres(env.DB_URL); ``` ### Set explicit parameters @@ -181,14 +181,14 @@ CREATE TABLE products ( Replace the existing code in your `worker.ts` file with the following code: ```typescript -import postgres from 'postgres' +import postgres from "postgres"; export default { async fetch(request, env, ctx): Promise { - const sql = postgres(connStr) + const sql = postgres(connStr); // Query the products table - const result = await sql`SELECT * FROM products;` + const result = await sql`SELECT * FROM products;`; // Return the result as JSON const resp = new Response(JSON.stringify(result), { @@ -223,25 +223,25 @@ Assume the `products` table has the following columns: `id`, `name`, `descriptio Add the following code snippet inside the `fetch` event handler in your `worker.ts` file, before the existing query code: ```typescript {9-32} -import postgres from 'postgres' +import postgres from "postgres"; export default { async fetch(request, env, ctx): Promise { - const sql = postgres(env.DB_URL) + const sql = postgres(env.DB_URL); - const url = new URL(request.url); + const url = new URL(request.url); if (request.method === "POST" && url.pathname === "/products") { // Parse the request's JSON payload const productData = await request.json(); // Insert the new product into the database const values = { - name: productData.name, - description: productData.description, - price: productData.price + name: productData.name, + description: productData.description, + price: productData.price, }; const insertResult = await sql` - INSERT INTO products ${ sql(values) } + INSERT INTO products ${sql(values)} RETURNING * `; @@ -255,7 +255,7 @@ export default { } // Query the products table - const result = await sql`SELECT * FROM products;` + const result = await sql`SELECT * FROM products;`; // Return the result as JSON const resp = new Response(JSON.stringify(result), { @@ -333,7 +333,7 @@ export default { const sql = postgres(env.HYPERDRIVE.connectionString) const url = new URL(request.url); - + //rest of the routes and database queries }, } satisfies ExportedHandler; @@ -350,7 +350,6 @@ npx wrangler deploy Your Worker application is now live and accessible at `..workers.dev`, using Hyperdrive. Hyperdrive accelerates database queries by pooling your connections and caching your requests across the globe. - ## Next steps To build more with databases and Workers, refer to [Tutorials](/workers/tutorials) and explore the [Databases documentation](/workers/databases). diff --git a/src/content/docs/workers/tutorials/upload-assets-with-r2/index.mdx b/src/content/docs/workers/tutorials/upload-assets-with-r2/index.mdx index 4261d3b9070af6..faea07c0dff9a2 100644 --- a/src/content/docs/workers/tutorials/upload-assets-with-r2/index.mdx +++ b/src/content/docs/workers/tutorials/upload-assets-with-r2/index.mdx @@ -36,9 +36,9 @@ First, use the [`create-cloudflare` CLI](https://github.com/cloudflare/workers-s file="c3-post-run-steps" product="workers" params={{ - one: "Hello World example", - two: "Hello World Worker", - three: "TypeScript", + category: "hello-world", + type: "Hello World Worker", + lang: "TypeScript", }} /> diff --git a/src/content/docs/workers/wrangler/api.mdx b/src/content/docs/workers/wrangler/api.mdx index 11de81a92ce0e3..e00ec77b23f06d 100644 --- a/src/content/docs/workers/wrangler/api.mdx +++ b/src/content/docs/workers/wrangler/api.mdx @@ -6,15 +6,14 @@ sidebar: head: [] description: A set of programmatic APIs that can be integrated with local Cloudflare Workers-related workflows. - --- -import { Render, TabItem, Tabs } from "~/components" +import { Render, TabItem, Tabs } from "~/components"; Wrangler offers APIs to programmatically interact with your Cloudflare Workers. -* [`unstable_dev`](#unstable_dev) - Start a server for running either end-to-end (e2e) or integration tests against your Worker. -* [`getPlatformProxy`](#getplatformproxy) - Get proxies and values for emulating the Cloudflare Workers platform in a Node.js process. +- [`unstable_dev`](#unstable_dev) - Start a server for running either end-to-end (e2e) or integration tests against your Worker. +- [`getPlatformProxy`](#getplatformproxy) - Get proxies and values for emulating the Cloudflare Workers platform in a Node.js process. ## `unstable_dev` @@ -26,52 +25,42 @@ By default, `unstable_dev` will perform integration tests against a local server :::note - The `unstable_dev()` function has an `unstable_` prefix because the API is experimental and may change in the future. `unstable_dev()` has no known bugs and is safe to use. If you discover any bugs, open a [GitHub issue](https://github.com/cloudflare/workers-sdk/issues/new/choose). - ::: ### Constructor ```js -const worker = await unstable_dev(script, options) +const worker = await unstable_dev(script, options); ``` ### Parameters +- `script` string + - A string containing a path to your Worker script, relative to your Worker project's root directory. -* `script` string - - * A string containing a path to your Worker script, relative to your Worker project's root directory. - -* `options` object optional - - * Optional options object containing `wrangler dev` configuration settings. - * Include an `experimental` object inside `options` to access experimental features such as `disableExperimentalWarning`. - * Set `disableExperimentalWarning` to `true` to disable Wrangler's warning about using `unstable_` prefixed APIs. - +- `options` object optional + - Optional options object containing `wrangler dev` configuration settings. + - Include an `experimental` object inside `options` to access experimental features such as `disableExperimentalWarning`. + - Set `disableExperimentalWarning` to `true` to disable Wrangler's warning about using `unstable_` prefixed APIs. ### Return Type `unstable_dev()` returns an object containing the following methods: +- `fetch()` `Promise` + - Send a request to your Worker. Returns a Promise that resolves with a [`Response`](/workers/runtime-apis/response) object. + - Refer to [`Fetch`](/workers/runtime-apis/fetch/). -* `fetch()` `Promise` - - * Send a request to your Worker. Returns a Promise that resolves with a [`Response`](/workers/runtime-apis/response) object. - * Refer to [`Fetch`](/workers/runtime-apis/fetch/). - -* `stop()` `Promise` - - * Shuts down the dev server. - +- `stop()` `Promise` + - Shuts down the dev server. ### Usage @@ -89,23 +78,23 @@ To wrap up a test suite, call `await worker.stop()` in an `afterAll` function. const { unstable_dev } = require("wrangler"); describe("Worker", () => { - let worker; - - beforeAll(async () => { - worker = await unstable_dev("src/index.js", { - experimental: { disableExperimentalWarning: true }, - }); - }); - - afterAll(async () => { - await worker.stop(); - }); - - it("should return Hello World", async () => { - const resp = await worker.fetch(); - const text = await resp.text(); - expect(text).toMatchInlineSnapshot(`"Hello World!"`); - }); + let worker; + + beforeAll(async () => { + worker = await unstable_dev("src/index.js", { + experimental: { disableExperimentalWarning: true }, + }); + }); + + afterAll(async () => { + await worker.stop(); + }); + + it("should return Hello World", async () => { + const resp = await worker.fetch(); + const text = await resp.text(); + expect(text).toMatchInlineSnapshot(`"Hello World!"`); + }); }); ``` @@ -116,23 +105,23 @@ import { unstable_dev } from "wrangler"; import type { UnstableDevWorker } from "wrangler"; describe("Worker", () => { - let worker: UnstableDevWorker; - - beforeAll(async () => { - worker = await unstable_dev("src/index.ts", { - experimental: { disableExperimentalWarning: true }, - }); - }); - - afterAll(async () => { - await worker.stop(); - }); - - it("should return Hello World", async () => { - const resp = await worker.fetch(); - const text = await resp.text(); - expect(text).toMatchInlineSnapshot(`"Hello World!"`); - }); + let worker: UnstableDevWorker; + + beforeAll(async () => { + worker = await unstable_dev("src/index.ts", { + experimental: { disableExperimentalWarning: true }, + }); + }); + + afterAll(async () => { + await worker.stop(); + }); + + it("should return Hello World", async () => { + const resp = await worker.fetch(); + const text = await resp.text(); + expect(text).toMatchInlineSnapshot(`"Hello World!"`); + }); }); ``` @@ -150,36 +139,36 @@ If you shut down the child Worker prematurely, the parent Worker will not know t import { unstable_dev } from "wrangler"; describe("multi-worker testing", () => { - let childWorker; - let parentWorker; - - beforeAll(async () => { - childWorker = await unstable_dev("src/child-worker.js", { - config: "src/child-wrangler.toml", - experimental: { disableExperimentalWarning: true }, - }); - parentWorker = await unstable_dev("src/parent-worker.js", { - config: "src/parent-wrangler.toml", - experimental: { disableExperimentalWarning: true }, - }); - }); - - afterAll(async () => { - await childWorker.stop(); - await parentWorker.stop(); - }); - - it("childWorker should return Hello World itself", async () => { - const resp = await childWorker.fetch(); - const text = await resp.text(); - expect(text).toMatchInlineSnapshot(`"Hello World!"`); - }); - - it("parentWorker should return Hello World by invoking the child worker", async () => { - const resp = await parentWorker.fetch(); - const parsedResp = await resp.text(); - expect(parsedResp).toEqual("Parent worker sees: Hello World!"); - }); + let childWorker; + let parentWorker; + + beforeAll(async () => { + childWorker = await unstable_dev("src/child-worker.js", { + config: "src/child-wrangler.toml", + experimental: { disableExperimentalWarning: true }, + }); + parentWorker = await unstable_dev("src/parent-worker.js", { + config: "src/parent-wrangler.toml", + experimental: { disableExperimentalWarning: true }, + }); + }); + + afterAll(async () => { + await childWorker.stop(); + await parentWorker.stop(); + }); + + it("childWorker should return Hello World itself", async () => { + const resp = await childWorker.fetch(); + const text = await resp.text(); + expect(text).toMatchInlineSnapshot(`"Hello World!"`); + }); + + it("parentWorker should return Hello World by invoking the child worker", async () => { + const resp = await parentWorker.fetch(); + const parsedResp = await resp.text(); + expect(parsedResp).toEqual("Parent worker sees: Hello World!"); + }); }); ``` @@ -190,36 +179,36 @@ import { unstable_dev } from "wrangler"; import type { UnstableDevWorker } from "wrangler"; describe("multi-worker testing", () => { - let childWorker: UnstableDevWorker; - let parentWorker: UnstableDevWorker; - - beforeAll(async () => { - childWorker = await unstable_dev("src/child-worker.js", { - config: "src/child-wrangler.toml", - experimental: { disableExperimentalWarning: true }, - }); - parentWorker = await unstable_dev("src/parent-worker.js", { - config: "src/parent-wrangler.toml", - experimental: { disableExperimentalWarning: true }, - }); - }); - - afterAll(async () => { - await childWorker.stop(); - await parentWorker.stop(); - }); - - it("childWorker should return Hello World itself", async () => { - const resp = await childWorker.fetch(); - const text = await resp.text(); - expect(text).toMatchInlineSnapshot(`"Hello World!"`); - }); - - it("parentWorker should return Hello World by invoking the child worker", async () => { - const resp = await parentWorker.fetch(); - const parsedResp = await resp.text(); - expect(parsedResp).toEqual("Parent worker sees: Hello World!"); - }); + let childWorker: UnstableDevWorker; + let parentWorker: UnstableDevWorker; + + beforeAll(async () => { + childWorker = await unstable_dev("src/child-worker.js", { + config: "src/child-wrangler.toml", + experimental: { disableExperimentalWarning: true }, + }); + parentWorker = await unstable_dev("src/parent-worker.js", { + config: "src/parent-wrangler.toml", + experimental: { disableExperimentalWarning: true }, + }); + }); + + afterAll(async () => { + await childWorker.stop(); + await parentWorker.stop(); + }); + + it("childWorker should return Hello World itself", async () => { + const resp = await childWorker.fetch(); + const text = await resp.text(); + expect(text).toMatchInlineSnapshot(`"Hello World!"`); + }); + + it("parentWorker should return Hello World by invoking the child worker", async () => { + const resp = await parentWorker.fetch(); + const parsedResp = await resp.text(); + expect(parsedResp).toEqual("Parent worker sees: Hello World!"); + }); }); ``` @@ -231,20 +220,16 @@ The `getPlatformProxy` function provides a way to obtain an object containing pr :::caution - `getPlatformProxy` is, by design, to be used exclusively in Node.js applications. `getPlatformProxy` cannot be run inside the Workers runtime. - ::: One general use case for getting a platform proxy is for emulating bindings in applications targeting Workers, but running outside the Workers runtime (for example, framework local development servers running in Node.js), or for testing purposes (for example, ensuring code properly interacts with a type of binding). :::note - Binding proxies provided by this function are a best effort emulation of the real production bindings. Although they are designed to be as close as possible to the real thing, there might be slight differences and inconsistencies between the two. - ::: ### Syntax @@ -255,17 +240,15 @@ const platform = await getPlatformProxy(options); ### Parameters +- `options` object optional + - Optional options object containing preferences for the bindings: -* `options` object optional - - * Optional options object containing preferences for the bindings: - - * `environment` string + - `environment` string The environment to use. - * `configPath` string + - `configPath` string The path to the config file to use. @@ -273,54 +256,48 @@ const platform = await getPlatformProxy(options); **Note:** this field is optional but if a path is specified it must point to a valid file on the filesystem. - * `experimentalJsonConfig` boolean + - `experimentalJsonConfig` boolean If `true`, allows the utility to read a JSON config file (for example, `wrangler.json`). - * `persist` boolean | `{ path: string }` + - `persist` boolean | `{ path: string }` Indicates if and where to persist the bindings data. If `true` or `undefined`, defaults to the same location used by Wrangler, so data can be shared between it and the caller. If `false`, no data is persisted to or read from the filesystem. **Note:** If you use `wrangler`'s `--persist-to` option, note that this option adds a sub directory called `v3` under the hood while `getPlatformProxy`'s `persist` does not. For example, if you run `wrangler dev --persist-to ./my-directory`, to reuse the same location using `getPlatformProxy`, you will have to specify: `persist: "./my-directory/v3"`. - - ### Return Type `getPlatformProxy()` returns a `Promise` resolving to an object containing the following fields. +- `env` `Record` + - Object containing proxies to bindings that can be used in the same way as production bindings. This matches the shape of the `env` object passed as the second argument to modules-format workers. These proxy to binding implementations run inside `workerd`. + - TypeScript Tip: `getPlatformProxy()` is a generic function. You can pass the shape of the bindings record as a type argument to get proper types without `unknown` values. -* `env` `Record` - - * Object containing proxies to bindings that can be used in the same way as production bindings. This matches the shape of the `env` object passed as the second argument to modules-format workers. These proxy to binding implementations run inside `workerd`. - * Typescript Tip: `getPlatformProxy()` is a generic function. You can pass the shape of the bindings record as a type argument to get proper types without `unknown` values. - -* `cf` IncomingRequestCfProperties read-only +- `cf` IncomingRequestCfProperties read-only - * Mock of the `Request`'s `cf` property, containing data similar to what you would see in production. + - Mock of the `Request`'s `cf` property, containing data similar to what you would see in production. -* `ctx` object +- `ctx` object - * Mock object containing implementations of the [`waitUntil`](/workers/runtime-apis/context/#waituntil) and [`passThroughOnException`](/workers/runtime-apis/context/#passthroughonexception) functions that do nothing. + - Mock object containing implementations of the [`waitUntil`](/workers/runtime-apis/context/#waituntil) and [`passThroughOnException`](/workers/runtime-apis/context/#passthroughonexception) functions that do nothing. -* `caches` object +- `caches` object - * Emulation of the [Workers `caches` runtime API](/workers/runtime-apis/cache/). - * For the time being, all cache operations do nothing. A more accurate emulation will be made available soon. - -* `dispose()` () => `Promise` - - * Terminates the underlying `workerd` process. - * Call this after the platform proxy is no longer required by the program. If you are running a long running process (such as a dev server) that can indefinitely make use of the proxy, you do not need to call this function. + - Emulation of the [Workers `caches` runtime API](/workers/runtime-apis/cache/). + - For the time being, all cache operations do nothing. A more accurate emulation will be made available soon. +- `dispose()` () => `Promise` + - Terminates the underlying `workerd` process. + - Call this after the platform proxy is no longer required by the program. If you are running a long running process (such as a dev server) that can indefinitely make use of the proxy, you do not need to call this function. ### Usage The `getPlatformProxy` function uses bindings found in `wrangler.toml`. For example, if you have an [environment variable](/workers/configuration/environment-variables/#add-environment-variables-via-wrangler) configuration set up in `wrangler.toml`: -```js +```toml [vars] MY_VARIABLE = "test" ``` @@ -347,15 +324,15 @@ All supported bindings found in your `wrangler.toml` are available to you via `e The bindings supported by `getPlatformProxy` are: -* [Environment variables](/workers/configuration/environment-variables/) +- [Environment variables](/workers/configuration/environment-variables/) -* [Service bindings](/workers/runtime-apis/bindings/service-bindings/) +- [Service bindings](/workers/runtime-apis/bindings/service-bindings/) -* [KV namespace bindings](/kv/api/) +- [KV namespace bindings](/kv/api/) -* [Durable Object bindings](/durable-objects/api/) +- [Durable Object bindings](/durable-objects/api/) - * To use a Durable Object binding with `getPlatformProxy`, always [specify a `script_name`](/workers/wrangler/configuration/#durable-objects) and have the target Worker run in a separate terminal via [`wrangler dev`](/workers/wrangler/commands/#dev). + - To use a Durable Object binding with `getPlatformProxy`, always [specify a `script_name`](/workers/wrangler/configuration/#durable-objects) and have the target Worker run in a separate terminal via [`wrangler dev`](/workers/wrangler/commands/#dev). For example, you might have the following file read by `getPlatformProxy`. @@ -370,12 +347,12 @@ The bindings supported by `getPlatformProxy` are: with a Durable Object declaration using the same `class_name` of `"MyDurableObject"` must be run separately via `wrangler dev`. -* [R2 bucket bindings](/r2/api/workers/workers-api-reference/) +- [R2 bucket bindings](/r2/api/workers/workers-api-reference/) -* [Queue bindings](/queues/configuration/javascript-apis/) +- [Queue bindings](/queues/configuration/javascript-apis/) -* [D1 database bindings](/d1/build-with-d1/d1-client-api/) +- [D1 database bindings](/d1/build-with-d1/d1-client-api/) -* [Workers AI bindings](/workers-ai/get-started/workers-wrangler/#2-connect-your-worker-to-workers-ai) +- [Workers AI bindings](/workers-ai/get-started/workers-wrangler/#2-connect-your-worker-to-workers-ai) diff --git a/src/content/partials/workers/c3-post-run-steps.mdx b/src/content/partials/workers/c3-post-run-steps.mdx index 9eb19a249d2f59..877dd4e55086a6 100644 --- a/src/content/partials/workers/c3-post-run-steps.mdx +++ b/src/content/partials/workers/c3-post-run-steps.mdx @@ -1,14 +1,30 @@ --- inputParameters: templateCategory;;templateType;;language - --- -import { Markdown } from "~/components" +import { Markdown } from "~/components"; For setup, select the following options: -* For *What would you like to start with?*, choose {props.one}. -* For *Which template would you like to use?*, choose {props.two}. -* For *Which language do you want to use?*, choose {props.three}. -* For *Do you want to use git for version control?*, choose `Yes`. -* For *Do you want to deploy your application?*, choose `No` (we will be making some changes before deploying). +{(function () { +switch (props.category) { +case 'hello-world': +return (
    + +
  • For What would you like to start with?, choose Hello World example.
  • +
  • For Which template would you like to use?, choose {props.type}.
  • +
  • For Which language do you want to use?, choose {props.lang}.
  • +
  • For Do you want to use git for version control?, choose Yes.
  • +
  • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).
  • +
); +case 'web-framework': +return (
    +
  • For What would you like to start with?, choose Framework Starter.
  • +
  • For Which development framework do you want to use?, choose {props.framework}.
  • +
  • Complete the framework's own CLI wizard.
  • +
  • For Do you want to use git for version control?, choose Yes.
  • +
  • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).
  • +
); +default: { +throw new Error(`[DOCS ERROR] UNKNOWN C3 CATEGORY: ${props.category}`); +}}})()} diff --git a/src/content/partials/workers/source-maps.mdx b/src/content/partials/workers/source-maps.mdx index a2d244c2fb3030..5d7408d7a0abe1 100644 --- a/src/content/partials/workers/source-maps.mdx +++ b/src/content/partials/workers/source-maps.mdx @@ -1,10 +1,9 @@ --- {} - --- [Stack traces](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack) help with debugging your code when your application encounters an unhandled exception. Stack traces show you the specific functions that were called, in what order, from which line and file, and with what arguments. -Most JavaScript code is first bundled, often transpiled, and then minified before being deployed to production. This process creates smaller bundles to optimize performance and converts code from Typescript to Javascript if needed. +Most JavaScript code is first bundled, often transpiled, and then minified before being deployed to production. This process creates smaller bundles to optimize performance and converts code from TypeScript to Javascript if needed. Source maps translate compiled and minified code back to the original code that you wrote. Source maps are combined with the stack trace returned by the JavaScript runtime to present you with a stack trace.