Skip to content

Commit ae1ec06

Browse files
authored
Update Cloudflare workers (#14963)
1 parent 41c5a10 commit ae1ec06

File tree

1 file changed

+45
-162
lines changed

1 file changed

+45
-162
lines changed
Lines changed: 45 additions & 162 deletions
Original file line numberDiff line numberDiff line change
@@ -1,192 +1,102 @@
11
---
22
title: Integrate TiDB Cloud with Cloudflare
3-
summary: Learn how deploy Cloudflare Workers with TiDB Cloud.
3+
summary: Learn how to deploy Cloudflare Workers with TiDB Cloud.
44
---
55

66
# Integrate TiDB Cloud with Cloudflare Workers
77

88
[Cloudflare Workers](https://workers.cloudflare.com/) is a platform that allows you to run code in response to specific events, such as HTTP requests or changes to a database. Cloudflare Workers is easy to use and can be used to build a variety of applications, including custom APIs, serverless functions, and microservices. It is particularly useful for applications that require low-latency performance or need to scale quickly.
99

10-
However, you may find it hard to connect to TiDB Cloud from Cloudflare Workers because Cloudflare Workers runs on the V8 engine which cannot make direct TCP connections.
10+
You may find it hard to connect to TiDB Cloud from Cloudflare Workers because Cloudflare Workers runs on the V8 engine which cannot make direct TCP connections. You can use [TiDB Cloud serverless driver](/tidb-cloud/serverless-driver.md) to help you connect to Cloudflare Workers over HTTP connection.
1111

12-
Fortunately, Prisma has your back with the [Data Proxy](https://www.prisma.io/docs/data-platform/data-proxy). It can help you use Cloudflare Workers to process and manipulate the data being transmitted over a TCP connection.
13-
14-
This document shows how to deploy Cloudflare Workers with TiDB Cloud and Prisma Data Proxy step by step.
12+
This document shows how to connect to Cloudflare Workers with TiDB Cloud serverless driver step by step.
1513

1614
> **Note:**
1715
>
18-
> If you want to connect a locally deployed TiDB to Cloudflare Workers, you can try [worker-tidb](https://github.com/shiyuhang0/worker-tidb), which uses Cloudflare tunnels as a proxy. However, worker-tidb is not recommended for production use.
16+
> TiDB Cloud serverless driver can only be used in TiDB Serverless.
1917
2018
## Before you begin
2119

2220
Before you try the steps in this article, you need to prepare the following things:
2321

2422
- A TiDB Cloud account and a TiDB Serverless cluster on TiDB Cloud. For more details, see [TiDB Cloud Quick Start](/tidb-cloud/tidb-cloud-quickstart.md#step-1-create-a-tidb-cluster).
2523
- A [Cloudflare Workers account](https://dash.cloudflare.com/login).
26-
- A [Prisma Data Platform account](https://cloud.prisma.io/).
27-
- A [GitHub account](https://github.com/login).
28-
- Install Node.js and npm.
29-
- Install dependencies using `npm install -D prisma typescript wrangler`
24+
- [npm](https://docs.npmjs.com/about-npm) is installed.
3025

3126
## Step 1: Set up Wrangler
3227

3328
[Wrangler](https://developers.cloudflare.com/workers/wrangler/) is the official Cloudflare Worker CLI. You can use it to generate, build, preview, and publish your Workers.
3429

35-
1. To authenticate Wrangler, run wrangler login:
30+
1. Install Wrangler:
31+
32+
```
33+
npm install wrangler
34+
```
35+
36+
2. To authenticate Wrangler, run wrangler login:
3637

3738
```
3839
wrangler login
3940
```
4041
41-
2. Use Wrangler to create a worker project:
42+
3. Use Wrangler to create a worker project:
4243
4344
```
44-
wrangler init prisma-tidb-cloudflare
45+
wrangler init tidb-cloud-cloudflare
4546
```
4647
47-
3. In your terminal, you will be asked a series of questions related to your project. Choose the default values for all questions.
48+
4. In your terminal, you will be asked a series of questions related to your project. Choose the default values for all questions.
4849
49-
## Step 2: Set up Prisma
50+
## Step 2: Install the serverless driver
5051
5152
1. Enter your project directory:
5253
5354
```
54-
cd prisma-tidb-cloudflare
55-
```
56-
57-
2. Use the `prisma init` command to set up Prisma:
58-
59-
```
60-
npx prisma init
55+
cd tidb-cloud-cloudflare
6156
```
6257
63-
This creates a Prisma schema in `prisma/schema.prisma`.
64-
65-
3. Inside `prisma/schema.prisma`, add the schema according to your tables in TiDB. Assume that you have `table1` and `table2` in TiDB, you can add the following schema:
58+
2. Install the serverless driver with npm:
6659
6760
```
68-
generator client {
69-
provider = "prisma-client-js"
70-
}
71-
72-
datasource db {
73-
provider = "mysql"
74-
url = env("DATABASE_URL")
75-
}
76-
77-
model table1 {
78-
id Int @id @default(autoincrement())
79-
name String
80-
}
81-
82-
model table2 {
83-
id Int @id @default(autoincrement())
84-
name String
85-
}
61+
npm install @tidbcloud/serverless
8662
```
8763
88-
This data model will be used to store incoming requests from your Worker.
89-
90-
## Step 3: Push your project to GitHub
64+
This adds the serverless driver dependency in `package.json`.
9165
92-
1. [Create a repository](https://github.com/new) named `prisma-tidb-cloudflare` on GitHub.
66+
## Step 3: Develop the Cloudflare Worker function
9367
94-
2. After you create the repository, you can push your project to GitHub:
95-
96-
```
97-
git remote add origin https://github.com/<username>/prisma-tidb-cloudflare
98-
git add .
99-
git commit -m "initial commit"
100-
git push -u origin main
101-
```
68+
You need to modify the `src/index.ts` according to your needs.
10269
103-
## Step 4: Import your Project into the Prisma Data Platform
104-
105-
With Cloudflare Workers, you cannot directly access your database because there is no TCP support. Instead, you can use Prisma Data Proxy as described above.
106-
107-
1. To get started, sign in to the [Prisma Data Platform](https://cloud.prisma.io/) and click **New Project**.
108-
2. Fill in the **Connection string** with this pattern `mysql://USER:PASSWORD@HOST:PORT/DATABASE?sslaccept=strict`. You can find the connection information in your [TiDB Cloud console](https://tidbcloud.com/console/clusters).
109-
3. Leave the **Static IPs** as disabled because TiDB Serverless is accessible from any IP address.
110-
4. Select a Data Proxy region that is geographically close to your TiDB Cloud cluster location. Then click **Create project**.
111-
112-
![Configure project settings](/media/tidb-cloud/cloudflare/cloudflare-project.png)
113-
114-
5. Fill in the repository, and click **Link Prisma schema** in the **Get Started** page.
115-
6. Click **Create a new connection string** and you will get a new connection string that starts with `prisma://.` Copy this connection string and save it for later.
116-
117-
![Create new connection string](/media/tidb-cloud/cloudflare/cloudflare-start.png)
118-
119-
7. Click **Skip and continue to Data Platform** to go to the Data Platform.
120-
121-
## Step 5: Set the Data Proxy Connection string in your environment
122-
123-
1. Add the Data Proxy connection string to your local environment `.env` file:
124-
125-
```
126-
DATABASE_URL=prisma://aws-us-east-1.prisma-data.com/?api_key=•••••••••••••••••"
127-
```
70+
For example, if you want to show all the databases, you can use the following code:
12871
129-
2. Add the Data Proxy connection to Cloudflare Workers with secret:
72+
```ts
73+
import { connect } from '@tidbcloud/serverless'
13074
131-
```
132-
wrangler secret put DATABASE_URL
133-
```
13475
135-
3. According to the prompt, enter the Data Proxy connection string.
76+
export interface Env {
77+
DATABASE_URL: string;
78+
}
13679
137-
> **Note:**
138-
>
139-
> You can also edit the `DATABASE_URL` secret via the Cloudflare Workers dashboard.
80+
export default {
81+
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
82+
const conn = connect({url:env.DATABASE_URL})
83+
const resp = await conn.execute("show databases")
84+
return new Response(JSON.stringify(resp));
85+
},
86+
};
87+
```
14088

141-
## Step 6: Generate a Prisma Client
89+
## Step 4: Set the DATABASE_URL in your environment
14290

143-
Generate a Prisma Client that connects through the [Data Proxy](https://www.prisma.io/docs/data-platform/data-proxy):
91+
The `DATABASE_URL` follows the `mysql://username:password@host/database` format. You can set the environment variable with wrangler cli:
14492

14593
```
146-
npx prisma generate --data-proxy
94+
wrangler secret put <DATABASE_URL>
14795
```
14896

149-
## Step 7: Develop the Cloudflare Worker function
150-
151-
You need to change the `src/index.ts` according to your needs.
152-
153-
For example, if you want to query different tables with an URL variable, you can use the following code:
154-
155-
```js
156-
import { PrismaClient } from '@prisma/client/edge'
157-
const prisma = new PrismaClient()
158-
159-
addEventListener('fetch', (event) => {
160-
event.respondWith(handleEvent(event))
161-
})
162-
163-
async function handleEvent(event: FetchEvent): Promise<Response> {
164-
// Get URL parameters
165-
const { request } = event
166-
const url = new URL(request.url);
167-
const table = url.searchParams.get('table');
168-
let limit = url.searchParams.get('limit');
169-
const limitNumber = limit? parseInt(limit): 100;
170-
171-
// Get model
172-
let model
173-
for (const [key, value] of Object.entries(prisma)) {
174-
if (typeof value == 'object' && key == table) {
175-
model = value
176-
break
177-
}
178-
}
179-
if(!model){
180-
return new Response("Table not defined")
181-
}
182-
183-
// Get data
184-
const result = await model.findMany({ take: limitNumber })
185-
return new Response(JSON.stringify({ result }))
186-
}
187-
```
97+
You can also edit the `DATABASE_URL` secret via the Cloudflare Workers dashboard.
18898

189-
## Step 8: Publish to Cloudflare Workers
99+
## Step 5: Publish to Cloudflare Workers
190100

191101
You're now ready to deploy to Cloudflare Workers.
192102

@@ -196,39 +106,12 @@ In your project directory, run the following command:
196106
npx wrangler publish
197107
```
198108

199-
## Step 9: Try your Cloudflare Workers
109+
## Step 6: Try your Cloudflare Workers
200110

201111
1. Go to [Cloudflare dashboard](https://dash.cloudflare.com) to find your worker. You can find the URL of your worker on the overview page.
202112

203-
2. Visit the URL with your table name: `https://{your-worker-url}/?table={table_name}`. You will get the result from the corresponding TiDB table.
204-
205-
## Update the project
206-
207-
### Change the serverless function
208-
209-
If you want to change the serverless function, update `src/index.ts` and publish it to Cloudflare Workers again.
210-
211-
### Create a new table
113+
2. Visit the URL and you will get the result.
212114

213-
If you create a new table and want to query it, take the following steps:
115+
## Examples
214116

215-
1. Add a new model in `prisma/schema.prisma`.
216-
2. Push the changes to your repository.
217-
218-
```
219-
git add prisma
220-
git commit -m "add new model"
221-
git push
222-
```
223-
224-
3. Generate the Prisma Client again.
225-
226-
```
227-
npx prisma generate --data-proxy
228-
```
229-
230-
4. Publish the Cloudflare Worker again.
231-
232-
```
233-
npx wrangler publish
234-
```
117+
See the [Cloudflare Workers example](https://github.com/tidbcloud/car-sales-insight/tree/main/examples/cloudflare-workers).

0 commit comments

Comments
 (0)