Appearance
在 Cloudflare Workers 上使用 Prisma
¥Using Prisma on Cloudflare Workers
Prisma ORM 提供了一个现代化且强大的数据库交互工具包。与 Hono 和 Cloudflare Workers 配合使用时,它可以帮助你在边缘部署高性能的无服务器应用。
¥Prisma ORM provides a modern, robust toolkit for interacting with databases. When paired with Hono and Cloudflare Workers, it enables you to deploy high-performance, serverless applications at the edge.
本指南将介绍在 Hono 中使用 Prisma ORM 的两种不同方法:
¥In this guide, we’ll cover two distinct approaches for using Prisma ORM in Hono:
Prisma Postgres:一个托管的、无服务器的 PostgreSQL 数据库与 Prisma 的集成。这种方法适用于生产环境,因为 Prisma Postgres 内置了连接池,支持零冷启动,可以缓解 无服务器和边缘环境中的扩展性问题 的问题。
¥Prisma Postgres: A managed, serverless PostgreSQL database integration with Prisma. This approach is good for a production-ready setup as Prisma Postgres has built-in connection pooling with zero-cold starts that mitigates scaling issues in serverless and edge environments.
驱动程序适配器:另一种方案是使用 Prisma 灵活的驱动程序适配器,允许你连接到 Prisma ORM 支持的任何数据库。
¥Driver adapters: An alternative that uses Prisma's flexible driver adapters, allowing you to connect to any database supported by Prisma ORM.
两种方法各有优势,你可以根据项目需求选择最合适的一种。
¥Both approaches have their own advantages, allowing you to choose the one that best fits your project's needs.
使用 Prisma Postgres
¥Using Prisma Postgres
Prisma Postgres 是一个基于单内核的托管式无服务器 PostgreSQL 数据库。它支持连接池、缓存和查询优化建议等功能。我们提供慷慨的免费套餐,供初始开发、测试和业余项目使用。
¥Prisma Postgres is a managed, serverless PostgreSQL database built on unikernels. It supports features like connection pooling, caching, and query optimization recommendations. A generous free tier is available for initial development, testing, and hobby projects.
1. 安装 Prisma 及所需依赖
¥ Install Prisma and required dependencies
在 Hono 项目中安装 Prisma:
¥Install Prisma in your Hono project:
bash
npm i prisma --save-dev安装 Prisma Postgres 所需的 Prisma 客户端扩展:
¥Install the Prisma client extension that's required for Prisma Postgres:
sh
npm i @prisma/extension-accelerate使用 Prisma Postgres 实例初始化 Prisma:
¥Initialize Prisma with an instance of Prisma Postgres:
bash
npx prisma@latest init --db如果你还没有 Prisma 数据平台 账户或未登录,该命令将提示你使用可用的身份验证提供程序之一登录。将打开一个浏览器窗口,以便你登录或创建账户。完成此步骤后,返回 CLI。
¥If you don't have a Prisma Data Platform account yet, or if you are not logged in, the command will prompt you to log in using one of the available authentication providers. A browser window will open so you can log in or create an account. Return to the CLI after you have completed this step.
登录后(或者如果你已经登录),CLI 将提示你选择项目名称和数据库区域。
¥Once logged in (or if you were already logged in), the CLI will prompt you to select a project name and a database region.
命令执行完毕后,它将创建:
¥Once the command has terminated, it has created:
你的 平台控制台 中包含一个 Prisma Postgres 数据库实例的项目。
¥A project in your Platform Console containing a Prisma Postgres database instance.
一个包含
schema.prisma的prisma文件夹,你可以在其中定义数据库模式。¥A
prismafolder containingschema.prisma, where you will define your database schema.项目根目录中的
.env文件将包含 Prisma Postgres 数据库 URLDATABASE_URL=<your-prisma-postgres-database-url>。¥An
.envfile in the project root, which will contain the Prisma Postgres database urlDATABASE_URL=<your-prisma-postgres-database-url>.
创建 .dev.vars 文件并将 DATABASE_URL 存储在其中:
¥Create a .dev.vars file and store the DATABASE_URL in it:
bash
DATABASE_URL="your_prisma_postgres_url"保留 .env 文件,以便 Prisma CLI 稍后可以访问它来执行迁移、生成 Prisma 客户端 或打开 Prisma Studio。
¥Keep the .env file so that Prisma CLI can access it later on to perform migrations, generate Prisma Client or to open Prisma Studio.
2. 在项目中设置 Prisma
¥ Set up Prisma in your project
现在,打开你的 schema.prisma 文件,并为你的数据库模式定义模型。例如,你可以添加一个 User 模型:
¥Now, open your schema.prisma file and define the models for your database schema. For example, you might add an User model:
ts
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String
name String
}使用 Prisma 迁移 将更改应用到数据库:
¥Use Prisma Migrate to apply changes to the database:
bash
npx prisma migrate dev创建一个类似这样的函数,以便稍后在项目中使用:
¥Create a function like this, which you can use in your project later:
ts
import { PrismaClient } from '@prisma/client/edge'
import { withAccelerate } from '@prisma/extension-accelerate'
export const getPrisma = (database_url: string) => {
const prisma = new PrismaClient({
datasourceUrl: database_url,
}).$extends(withAccelerate())
return prisma
}以下示例展示了如何在你的项目中使用此函数:
¥Here is an example of how you can use this function in your project:
ts
import { Hono } from 'hono'
import { sign, verify } from 'hono/jwt'
import { getPrisma } from '../usefulFun/prismaFun'
// Create the main Hono app
const app = new Hono<{
Bindings: {
DATABASE_URL: string
JWT_SECRET: string
}
Variables: {
userId: string
}
}>()
app.post('/', async (c) => {
// Now you can use it wherever you want
const prisma = getPrisma(c.env.DATABASE_URL)
})如果你想将自己的数据库与 Prisma ORM 结合使用,并受益于连接池和边缘缓存,可以启用 Prisma Accelerate。了解更多关于如何为你的项目设置 Prisma Accelerate 的信息。
¥If you want to use your own database with Prisma ORM and benefit from connection pooling and edge caching, you can enable Prisma Accelerate. Learn more about setting up Prisma Accelerate for your project.
使用 Prisma 驱动程序适配器
¥Using Prisma Driver Adapters
Prisma 可以通过 driverAdapters 与 D1 数据库配合使用。前提条件是安装 Prisma 并集成 Wrangler 以绑定到你的 Hono 项目。这是一个示例项目,因为 Hono、Prisma 和 D1 Cloudflare 的所有文档都是独立的,没有精确的逐步说明。
¥Prisma can be used with the D1 Database via driverAdapters. The prerequisites are to install Prisma and integrate Wrangler to bind with your Hono project. This is an example project since all documentation for Hono, Prisma, and D1 Cloudflare is separated and doesn't have exact, precise step-by-step instructions.
设置 Prisma
¥Setup Prisma
Prisma 和 D1 使用 Wrangler 中的绑定来确保与适配器的连接安全。
¥Prisma and D1 are using a binding in Wrangler to secure a connection with an adapter.
bash
npm install prisma --save-dev
npx prisma init
npm install @prisma/client
npm install @prisma/adapter-d1之后,Prisma 将为你的数据库生成 schema;在 prisma/schema.prisma 中定义一个简单的模型。不要忘记更改适配器。
¥After this, Prisma will generate schema for your database; define a simple model in prisma/schema.prisma. Don't forget to change the adapter.
ts
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"] // change from default
}
datasource db {
provider = "sqlite" // d1 is sql base database
url = env("DATABASE_URL")
}
// Create a simple model database
model User {
id String @id @default(uuid())
email String @unique
name String?
}D1 数据库
¥D1 Database
如果你已经准备好 D1 数据库,请跳过此步骤。如果需要,你可以创建一个资源,该资源可在 此处 中找到。
¥If you already have D1 database ready skip this. But if not, create one resources, which can be found in here.
bash
npx wrangler d1 create __DATABASE_NAME__ // change it with yours确保你的数据库绑定到 wrangler.toml。
¥Make sure your DB is binding in wrangler.toml.
toml
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "__DATABASE_NAME__"
database_id = "DATABASE ID"Prisma 迁移
¥Prisma Migrate
此命令用于迁移 Prisma 并切换到 D1 数据库(本地或远程)。
¥This command makes to migrate Prisma and change to the D1 database, either local or remote.
bash
npx wrangler d1 migrations create __DATABASE_NAME__ create_user_table # will generate migration folder and sql file
// for generate sql statement
npx prisma migrate diff \
--from-empty \
--to-schema-datamodel ./prisma/schema.prisma \
--script \
--output migrations/0001_create_user_table.sql将数据库模型迁移到 D1。
¥Migrate the database model to D1.
bash
npx wrangler d1 migrations apply __DATABASE_NAME__ --local
npx wrangler d1 migrations apply __DATABASE_NAME__ --remote
npx prisma generate配置 Prisma 客户端
¥Config Prisma Client
要使用 Prisma 从 D1 数据库查询你的数据库,你需要添加以下类型:
¥In order to query your database from the D1 database using Prisma, you need to add types with:
bash
npx wrangler types将生成一个 worker-configuration.d.ts 文件。
¥will generate a worker-configuration.d.ts file.
Prisma 客户端
¥Prisma Clients
要全局使用 Prisma,请创建一个名为 lib/prismaClient.ts 的文件,并添加类似如下的代码。
¥For using Prisma globally make a file lib/prismaClient.ts with code like this.
ts
import { PrismaClient } from '@prisma/client'
import { PrismaD1 } from '@prisma/adapter-d1'
const prismaClients = {
async fetch(db: D1Database) {
const adapter = new PrismaD1(db)
const prisma = new PrismaClient({ adapter })
return prisma
},
}
export default prismaClients将 Hono 与 Wrangler 环境变量绑定:
¥Binding Hono with wrangler environment values:
ts
import { Hono } from 'hono'
import prismaClients from '../lib/prismaClient'
type Bindings = {
MY_KV: KVNamespace
DB: D1Database
}
const app = new Hono<{ Bindings: Bindings }>() // binding env valueHono 路由使用示例:
¥Example of use in Hono route:
ts
import { Hono } from 'hono'
import prismaClients from '../lib/prismaClient'
type Bindings = {
MY_KV: KVNamespace
DB: D1Database
}
const app = new Hono<{ Bindings: Bindings }>()
app.get('/', async (c) => {
const prisma = await prismaClients.fetch(c.env.DB)
const users = await prisma.user.findMany()
console.log('users', users)
return c.json(users)
})
export default app这将返回 / 路由中的所有用户,你可以使用 Postman 或 Thunder Client 查看结果。
¥This will return all users in the / route, using Postman or Thunder Client to see the result.
资源
¥Resources
你可以使用以下资源进一步增强你的应用:
¥You can use the following resources to enhance your application further:
将 caching 添加到你的查询中。
¥Add caching to your queries.
¥Explore the Prisma Postgres documentation.