|
1 | 1 | --- |
2 | 2 | pcx_content_type: navigation |
3 | | -title: Worker Binding API |
| 3 | +title: D1 Worker Binding API |
4 | 4 | sidebar: |
5 | 5 | order: 4 |
6 | | - group: |
7 | | - hideIndex: true |
8 | 6 | --- |
9 | 7 |
|
10 | | -import { DirectoryListing } from "~/components"; |
| 8 | +import { DirectoryListing, Details, Steps } from "~/components"; |
| 9 | + |
| 10 | +You can execute queries on your D1 database through SQL query statements. To do this, you need to perform the following steps: |
| 11 | + |
| 12 | +1. [Prepare a statement](/d1/worker-api/prepare-a-statement). |
| 13 | +2. [Run the prepared statement](/d1/worker-api/run-a-statement). |
| 14 | +3. Analyze the [return object](/d1/worker-api/return-object) (if necessary). |
| 15 | + |
| 16 | +Refer to the relevant sections for the API documentation. |
| 17 | + |
| 18 | +## Typescript support |
| 19 | + |
| 20 | +D1 Worker Bindings API is fully-typed via the `@cloudflare/workers-types` package, and also supports [generic types](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types) as part of its TypeScript API. A generic type allows you to provide an optional _type parameter_ so that a function understands the type of the data it is handling. |
| 21 | + |
| 22 | +When using the [query statement methods](#query-statement-methods) `stmt.run()`, `stmt.raw()` and `stmt.first()`, you can provide a type representing each database row. D1's API will [return the result object](#return-object) with the correct type. |
| 23 | + |
| 24 | +For example, providing an `OrderRow` type as a type parameter to `stmt.run()` will return a typed `Array<OrderRow>` object instead of the default `Record<string, unknown>` type: |
| 25 | + |
| 26 | +```ts |
| 27 | +// Row definition |
| 28 | +type OrderRow = { |
| 29 | +Id: string; |
| 30 | +CustomerName: string; |
| 31 | +OrderDate: number; |
| 32 | +}; |
| 33 | + |
| 34 | +// Elsewhere in your application |
| 35 | +const result = await env.MY_DB.prepare( |
| 36 | +"SELECT Id, CustomerName, OrderDate FROM [Order] ORDER BY ShippedDate DESC LIMIT 100", |
| 37 | +).run<OrderRow>(); |
| 38 | +``` |
| 39 | + |
| 40 | +## API playground |
| 41 | + |
| 42 | +The D1 Worker Binding API playground is an `index.js` file where you can test each of the documented Worker Binding APIs for D1. The file builds from the end-state of the [Get started](/d1/get-started/#write-queries-within-your-worker) code. |
| 43 | + |
| 44 | +You can use this alongside the API documentation to better understand how each API works. |
| 45 | + |
| 46 | +Follow the steps to setup your API playground. |
| 47 | + |
| 48 | +### 1. Complete the Get started tutorial |
| 49 | + |
| 50 | +Complete the [Get started](/d1/get-started/#write-queries-within-your-worker) tutorial. Ensure you use JavaScript instead of TypeScript. |
| 51 | + |
| 52 | +### 2. Modify the content of `index.js` |
| 53 | + |
| 54 | +Replace the contents of your `index.js` file with the below to view the effect of each API. |
| 55 | + |
| 56 | +<Details header="index.js" open={false}> |
| 57 | +```js |
| 58 | +export default { |
| 59 | + async fetch(request, env) { |
| 60 | + const { pathname } = new URL(request.url); |
| 61 | + |
| 62 | + const companyName1 = `Bs Beverages`; |
| 63 | + const companyName2 = `Around the Horn`; |
| 64 | + const stmt = env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`); |
| 65 | + |
| 66 | + if (pathname === `/RUN`){ |
| 67 | + const returnValue = await stmt.bind(companyName1).run() |
| 68 | + return Response.json(returnValue); |
| 69 | + |
| 70 | + } else if (pathname === `/RAW`){ |
| 71 | + const returnValue = await stmt.bind(companyName1).raw(); |
| 72 | + return Response.json(returnValue); |
| 73 | + |
| 74 | + } else if (pathname === `/FIRST`){ |
| 75 | + const returnValue = await stmt.bind(companyName1).first(); |
| 76 | + return Response.json(returnValue); |
| 77 | + |
| 78 | + } else if (pathname === `/BATCH`) { |
| 79 | + const batchResult = await env.DB.batch([ |
| 80 | + stmt.bind(companyName1), |
| 81 | + stmt.bind(companyName2) |
| 82 | + ]); |
| 83 | + // const returnValue = await stmt.run(); |
| 84 | + return Response.json(batchResult); |
| 85 | + } |
| 86 | + |
| 87 | + return new Response( |
| 88 | + `Welcome to the D1 API Playground! |
| 89 | + \nChange the URL to test the methods inside your index.js file.`, |
| 90 | + ); |
| 91 | + }, |
| 92 | + }; |
| 93 | + |
| 94 | +``` |
| 95 | +</Details> |
| 96 | + |
| 97 | +### 3. Deploy the Worker |
| 98 | + |
| 99 | +<Steps> |
| 100 | +1. Navigate to your tutorial directory you created by following step 1. |
| 101 | +2. Run `npx wrangler dev`. |
| 102 | + ```sh |
| 103 | + npx wrangler dev |
| 104 | + ``` |
| 105 | + ```sh output |
| 106 | + ⛅️ wrangler 3.85.0 (update available 3.86.1) |
| 107 | + ------------------------------------------------------- |
| 108 | + |
| 109 | + Your worker has access to the following bindings: |
| 110 | + - D1 Databases: |
| 111 | + - DB: <DATABASE_NAME> (DATABASE_ID) (local) |
| 112 | + ⎔ Starting local server... |
| 113 | + [wrangler:inf] Ready on http://localhost:8787 |
| 114 | + ╭───────────────────────────╮ |
| 115 | + │ [b] open a browser │ |
| 116 | + │ [d] open devtools │ |
| 117 | + │ [l] turn off local mode │ |
| 118 | + │ [c] clear console │ |
| 119 | + │ [x] to exit │ |
| 120 | + ╰───────────────────────────╯ |
| 121 | + ``` |
| 122 | +3. Open a browser at the specified address. |
| 123 | +</Steps> |
| 124 | + |
| 125 | +### 4. Test the APIs |
| 126 | + |
| 127 | +Change the URL to test the various D1 Worker Binding APIs. |
11 | 128 |
|
12 | | -<DirectoryListing /> |
|
0 commit comments