Skip to main content

如何将 Prisma ORM 和 Prisma Postgres 与 Cloudflare Workers 结合使用

15 min

介绍

¥Introduction

Prisma ORM 提供类型安全的数据库访问,而 Cloudflare Workers 则支持在边缘部署无服务器代码。结合 Prisma Postgres,你将获得一个全球分布式后端,并可实现低延迟的数据库访问。

¥Prisma ORM provides type-safe database access, and Cloudflare Workers enables you to deploy serverless code at the edge. Together with Prisma Postgres, you get a globally distributed backend with low-latency database access.

在本指南中,你将学习如何在 Cloudflare Workers 项目中将 Prisma ORM 与 Prisma Postgres 数据库集成。你可以在 GitHub 上找到本指南的完整示例。

¥In this guide, you'll learn to integrate Prisma ORM with a Prisma Postgres database in a Cloudflare Workers project. You can find a complete example of this guide on GitHub.

先决条件

¥Prerequisites

1. 设置你的项目

¥ Set up your project

创建一个新的 Cloudflare Workers 项目:

¥Create a new Cloudflare Workers project:

npm create cloudflare@latest prisma-cloudflare-worker -- --type=hello-world --ts=true --git=true --deploy=false

进入新创建的项目目录:

¥Navigate into the newly created project directory:

cd prisma-cloudflare-worker

2. 安装和配置 Prisma

¥ Install and configure Prisma

2.1.安装依赖

¥2.1. Install dependencies

要开始使用 Prisma,你需要安装一些依赖:

¥To get started with Prisma, you'll need to install a few dependencies:

npm install prisma dotenv-cli @types/pg --save-dev
npm install @prisma/client @prisma/adapter-pg dotenv pg
信息

如果你使用其他数据库提供商(MySQL、SQL Server、SQLite),请安装相应的驱动程序适配器包,而不是 @prisma/adapter-pg。欲了解更多信息,请参阅 数据库驱动程序

¥If you are using a different database provider (MySQL, SQL Server, SQLite), install the corresponding driver adapter package instead of @prisma/adapter-pg. For more information, see Database drivers.

安装完成后,请在你的项目中初始化 Prisma:

¥Once installed, initialize Prisma in your project:

npx prisma init --db
信息

在设置 Prisma Postgres 数据库时,你需要回答几个问题。选择离你最近的区域,并为数据库选择一个容易记住的名称,例如 "我的 Cloudflare Workers 项目"

¥You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My Cloudflare Workers Project"

这将造成:

¥This will create:

  • 一个包含 schema.prisma 文件的 prisma/ 目录

    ¥A prisma/ directory with a schema.prisma file

  • 包含 Prisma 配置的 prisma.config.ts 文件

    ¥A prisma.config.ts file with your Prisma configuration

  • 一个已设置 DATABASE_URL.env 文件

    ¥A .env file with a DATABASE_URL already set

2.2.在 Cloudflare Workers 中启用 Node.js 兼容性

¥2.2. Enable Node.js compatibility in Cloudflare Workers

Cloudflare Workers 需要启用 Node.js 兼容性才能与 Prisma 配合使用。向 wrangler.jsonc 添加 nodejs_compat 兼容性标志。

¥Cloudflare Workers needs Node.js compatibility enabled to work with Prisma. Add the nodejs_compat compatibility flag to your wrangler.jsonc:

wrangler.jsonc
{
"name": "prisma-cloudflare-worker",
"main": "src/index.ts",
"compatibility_flags": ["nodejs_compat"],
"compatibility_date": "2024-01-01"
}

2.3.定义 Prisma Schema

¥2.3. Define your Prisma Schema

prisma/schema.prisma 文件中,添加以下 User 模型,并将运行时设置为 cloudflare

¥In the prisma/schema.prisma file, add the following User model and set the runtime to cloudflare:

prisma/schema.prisma
generator client {
provider = "prisma-client"
runtime = "cloudflare"
output = "../src/generated/prisma"
}

datasource db {
provider = "postgresql"
}

model User {
id Int @id @default(autoincrement())
email String
name String
}
注意

支持 cloudflareworkerd 运行时。了解更多关于运行时 此处 的信息。

¥Both the cloudflare and workerd runtimes are supported. Read more about runtimes here.

这将创建一个具有自增 ID、电子邮件和名称的 User 模型。

¥This creates a User model with an auto-incrementing ID, email, and name.

2.4.配置 Prisma 脚本

¥2.4. Configure Prisma scripts

将以下脚本添加到你的 package.json 文件中,以便在 Cloudflare Workers 环境中使用 Prisma:

¥Add the following scripts to your package.json to work with Prisma in the Cloudflare Workers environment:

package.json
{
"scripts": {
"migrate": "prisma migrate dev",
"generate": "prisma generate",
"studio": "prisma studio"
// ... existing scripts
}
}

2.5.运行迁移并生成 Prisma 客户端

¥2.5. Run migrations and generate Prisma Client

现在,运行以下命令创建数据库表:

¥Now, run the following command to create the database tables:

npm run migrate

出现提示时,请为你的迁移命名(例如,init)。

¥When prompted, name your migration (e.g., init).

然后生成 Prisma 客户端:

¥Then generate the Prisma Client:

npm run generate

此操作会在 src/generated/prisma/client 目录中生成 Prisma 客户端。

¥This generates the Prisma Client in the src/generated/prisma/client directory.

3. 将 Prisma 集成到 Cloudflare Workers

¥ Integrate Prisma into Cloudflare Workers

3.1.导入 Prisma 客户端并配置类型

¥3.1. Import Prisma Client and configure types

src/index.ts 的顶部,导入生成的 Prisma Client 和 PostgreSQL 适配器,并定义用于类型安全环境变量的 Env 接口:

¥At the top of src/index.ts, import the generated Prisma Client and the PostgreSQL adapter, and define the Env interface for type-safe environment variables:

src/index.ts
import { PrismaClient } from './generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';

export interface Env {
DATABASE_URL: string;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
return new Response('Hello World!');
},
} satisfies ExportedHandler<Env>;

3.2.处理网站图标请求

¥3.2. Handle favicon requests

添加一个检查来过滤掉 favicon 请求,浏览器会自动发送这些请求,导致日志过于冗杂:

¥Add a check to filter out favicon requests, which browsers automatically send and can clutter your logs:

src/index.ts
import { PrismaClient } from './generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';

export interface Env {
DATABASE_URL: string;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const path = new URL(request.url).pathname;
if (path === '/favicon.ico')
return new Response('Resource not found', {
status: 404,
headers: {
'Content-Type': 'text/plain',
},
});

return new Response('Hello World!');
},
} satisfies ExportedHandler<Env>;

3.3.初始化 Prisma 客户端

¥3.3. Initialize the Prisma Client

创建数据库适配器并使用它初始化 Prisma Client。在边缘环境中,必须对每个请求执行此操作:

¥Create a database adapter and initialize Prisma Client with it. This must be done for each request in edge environments:

src/index.ts
import { PrismaClient } from './generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';

export interface Env {
DATABASE_URL: string;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const path = new URL(request.url).pathname;
if (path === '/favicon.ico')
return new Response('Resource not found', {
status: 404,
headers: {
'Content-Type': 'text/plain',
},
});

const adapter = new PrismaPg({
connectionString: env.DATABASE_URL,
});

const prisma = new PrismaClient({
adapter,
});

return new Response('Hello World!');
},
} satisfies ExportedHandler<Env>;
警告

在 Cloudflare Workers 等边缘环境中,每个请求都会创建一个新的 Prisma Client 实例。这与长时间运行的 Node.js 服务器不同,在长时间运行的服务器中,你通常会实例化单个客户端并重复使用它。

¥In edge environments like Cloudflare Workers, you create a new Prisma Client instance per request. This is different from long-running Node.js servers where you typically instantiate a single client and reuse it.

3.4.创建用户并查询数据库

¥3.4. Create a user and query the database

现在使用 Prisma Client 创建一个新用户并统计用户总数:

¥Now use Prisma Client to create a new user and count the total number of users:

src/index.ts
import { PrismaClient } from './generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';

export interface Env {
DATABASE_URL: string;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const path = new URL(request.url).pathname;
if (path === '/favicon.ico')
return new Response('Resource not found', {
status: 404,
headers: {
'Content-Type': 'text/plain',
},
});

const adapter = new PrismaPg({
connectionString: env.DATABASE_URL,
});

const prisma = new PrismaClient({
adapter,
});

const user = await prisma.user.create({
data: {
email: `Prisma-Postgres-User-${Math.ceil(Math.random() * 1000)}@gmail.com`,
name: 'Jon Doe',
},
});

const userCount = await prisma.user.count();

return new Response('Hello World!');
},
} satisfies ExportedHandler<Env>;

3.5.返回结果

¥3.5. Return the results

最后,更新响应以显示新创建的用户和用户总数:

¥Finally, update the response to display the newly created user and the total user count:

src/index.ts
import { PrismaClient } from './generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';

export interface Env {
DATABASE_URL: string;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const path = new URL(request.url).pathname;
if (path === '/favicon.ico')
return new Response('Resource not found', {
status: 404,
headers: {
'Content-Type': 'text/plain',
},
});

const adapter = new PrismaPg({
connectionString: env.DATABASE_URL,
});

const prisma = new PrismaClient({
adapter,
});

const user = await prisma.user.create({
data: {
email: `Prisma-Postgres-User-${Math.ceil(Math.random() * 1000)}@gmail.com`,
name: 'Jon Doe',
},
});

const userCount = await prisma.user.count();

return new Response(`\
Created new user: ${user.name} (${user.email}).
Number of users in the database: ${userCount}.
`);
},
} satisfies ExportedHandler<Env>;

3.6.在本地测试 Worker

¥3.6. Test your Worker locally

首先,为你的 Worker 环境生成 TypeScript 类型:

¥First, generate the TypeScript types for your Worker environment:

npx wrangler types --no-strict-vars

然后启动开发服务器:

¥Then start the development server:

npm run dev

在浏览器中打开 http://localhost:8787 文件。每次刷新页面时,都会创建一个新用户。你应该看到类似以下内容的输出:

¥Open http://localhost:8787 in your browser. Each time you refresh the page, a new user will be created. You should see output similar to:

Created new user: Jon Doe (Prisma-Postgres-User-742@gmail.com).
Number of users in the database: 5.

3.7.使用 Prisma Studio 检查数据

¥3.7. Inspect your data with Prisma Studio

要查看数据库内容,请打开 Prisma Studio:

¥To view your database contents, open Prisma Studio:

npm run studio

这将打开一个浏览器窗口,你可以在其中查看和编辑 User 表数据。

¥This will open a browser window where you can view and edit your User table data.

4. 部署到 Cloudflare Workers

¥ Deploy to Cloudflare Workers

4.1.将数据库 URL 设置为密钥

¥4.1. Set your database URL as a secret

部署前,你需要在 Cloudflare Workers 中将 DATABASE_URL 设置为密钥。它能确保生产环境中数据库连接字符串的安全。

¥Before deploying, you need to set your DATABASE_URL as a secret in Cloudflare Workers. This keeps your database connection string secure in production.

npx wrangler secret put DATABASE_URL

出现提示时,请粘贴 .env 文件中的数据库连接字符串。

¥When prompted, paste your database connection string from the .env file.

4.2.部署你的 Worker

¥4.2. Deploy your Worker

将你的 Worker 部署到 Cloudflare

¥Deploy your Worker to Cloudflare:

npm run deploy

部署完成后,Cloudflare 将为你提供一个 URL,你的 Worker 将在该 URL 上运行(例如,https://prisma-postgres-worker.your-subdomain.workers.dev)。

¥Once deployed, Cloudflare will provide you with a URL where your Worker is live (e.g., https://prisma-postgres-worker.your-subdomain.workers.dev).

在浏览器中访问此 URL,你将看到你的 Worker 在生产环境中创建用户!

¥Visit the URL in your browser, and you'll see your Worker creating users in production!

概括

¥Summary

你已成功创建使用 Prisma ORM 连接到 Prisma Postgres 数据库的 Cloudflare Workers 应用。你的 Worker 现在正在边缘运行,可实现低延迟数据库访问。

¥You've successfully created a Cloudflare Workers application with Prisma ORM connected to a Prisma Postgres database. Your Worker is now running at the edge with low-latency database access.

下一步

¥Next steps

现在你已经拥有一个运行正常的 Cloudflare Workers 应用并连接到 Prisma Postgres 数据库,你可以:

¥Now that you have a working Cloudflare Workers app connected to a Prisma Postgres database, you can:

  • 添加路由以处理不同的 HTTP 方法(GET、POST、PUT、DELETE)。

    ¥Add routes to handle different HTTP methods (GET, POST, PUT, DELETE)

  • 使用更多模型和关系扩展你的 Prisma 模式

    ¥Extend your Prisma schema with more models and relationships

  • 实现身份验证和授权

    ¥Implement authentication and authorization

  • 使用 Hono 可获得更强大的路由框架,并支持 Cloudflare Workers(请参阅我们的 Hono 指南

    ¥Use Hono for a more robust routing framework with Cloudflare Workers (see our Hono guide)

  • 使用 Prisma Postgres 启用查询缓存以获得更好的性能

    ¥Enable query caching with Prisma Postgres for better performance

更多信息

¥More info


Stay connected with Prisma

Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:

We genuinely value your involvement and look forward to having you as part of our community!