Appearance
在 Cloudflare Workers 上使用 Prisma
🌐 Using Prisma on Cloudflare Workers
Prisma ORM 提供了一个用于与数据库交互的现代、强大的工具包。当与 Hono 和 Cloudflare Workers 配合使用时,它可以让你在边缘部署高性能的无服务器应用。
本指南将介绍在 Hono 中使用 Prisma ORM 的两种不同方法:
🌐 In this guide, we’ll cover two distinct approaches for using Prisma ORM in Hono:
- Prisma Postgres:一个与 Prisma 集成的托管、无服务器 PostgreSQL 数据库。这种方法适合生产环境的设置,因为 Prisma Postgres 内置了连接池,并且零冷启动,从而缓解了 无服务器和边缘环境中的扩展问题。
- 驱动适配器:一种使用 Prisma 灵活驱动适配器的替代方案,允许你连接到 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 数据库,构建在 unikernels 上。它支持连接池、缓存和查询优化建议等功能。提供了丰富的免费套餐,适用于初始开发、测试和业余项目。
1. 安装 Prisma 及所需依赖
🌐 1. 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 数据平台 账户,或者尚未登录,该命令将提示你使用可用的认证提供者之一进行登录。将会打开一个浏览器窗口,以便你登录或创建账户。完成此步骤后,请返回命令行接口。
🌐 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 数据库实例。
- 一个包含
schema.prisma的prisma文件夹,你将在其中定义你的数据库模式。 - 项目根目录下的
.env文件,其中将包含 Prisma Postgres 数据库 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 Client 或打开 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
🌐 2. 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 Migrate 将更改应用到数据库:
🌐 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。
- 浏览 Prisma Postgres 文档。