Skip to main content

如何在 Bun 中使用 Prisma

10 min

介绍

¥Introduction

Bun 是一个快速的 JavaScript 运行时,包含打包器、测试运行器和包管理器。在本指南中,你将使用 Prisma ORM 和 Prisma Postgres 数据库设置一个 Bun 项目。你将配置 Prisma 驱动程序适配器,创建一个简单的 HTTP 服务器,并构建一个用于部署的 Bun 可执行文件。

¥Bun is a fast JavaScript runtime that includes a bundler, test runner, and package manager. In this guide, you will set up a Bun project with Prisma ORM and a Prisma Postgres database. You will configure Prisma driver adapters, create a simple HTTP server, and build a Bun executable for deployment.

先决条件

¥Prerequisites

1. 设置你的 Bun 项目

¥ Setting up your Bun project

首先,为你的项目创建一个目录并导航到该目录:

¥First, create a directory for your project and navigate to it:

mkdir bun-prisma
cd bun-prisma

然后,初始化一个新的 Bun 项目:

¥Then, initialise a new Bun project:

bun init -y

这将创建一个包含 package.json 文件和 index.ts 文件的基本 Bun 项目。

¥This creates a basic Bun project that includes a package.json file and an index.ts file.

2. 安装和配置 Prisma

¥ Installing and configuring Prisma

2.1.安装依赖

¥2.1. Install dependencies

安装所需的 Prisma 软件包和其他依赖:

¥Install the required Prisma packages and other dependencies:

bun add -d prisma
bun add @prisma/client @prisma/adapter-pg dotenv

2.2.使用 Prisma Postgres 初始化 Prisma ORM

¥2.2. Initialize Prisma ORM with Prisma Postgres

在你的项目中使用 Prisma Postgres 初始化 Prisma ORM:

¥Initialize Prisma ORM with Prisma Postgres in your project:

bun prisma init --db
信息

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

¥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 Bun Project"

此命令将创建:

¥This command creates:

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

    ¥A prisma/ directory with your schema.prisma file

  • 一个新的 Prisma Postgres 数据库

    ¥A new Prisma Postgres database

  • 包含你的 DATABASE_URL 文件的 .env 文件

    ¥A .env file with your DATABASE_URL

2.3.为驱动程序适配器配置环境变量

¥2.3. Configure environment variables for driver adapters

我们将使用 node-postgres 驱动适配器 对数据库执行查询。

¥We are going to use the node-postgres driver adapter to perform queries to our database.

node-postgres 驱动程序适配器与 Prisma Postgres 结合使用时,你需要添加 DIRECT_URL 环境变量。这提供了与 PostgreSQL 数据库的直接连接。

¥When using the node-postgres driver adapter with Prisma Postgres, you need to add a DIRECT_URL environment variable. This provides a direct connection to your PostgreSQL database.

获取你的 直接连接字符串

¥To get your direct connection string:

  1. 导航至你最近创建的 Prisma Postgres 项目仪表板(例如 "我的 Bun 项目")

    ¥Navigate to your recently created Prisma Postgres project dashboard (e.g. "My Bun Project")

  2. 点击项目侧边栏中的“API 密钥”选项卡

    ¥Click the API Keys tab in the project's sidebar

  3. 点击“创建 API 密钥”按钮

    ¥Click the Create API key button

  4. 输入 API 密钥的名称,然后点击“创建”。

    ¥Provide a name for the API key and click Create

  5. 复制以 postgres:// 开头的连接字符串

    ¥Copy the connection string starting with postgres://

更新你的 .env 文件以包含这两个 URL:

¥Update your .env file to include both URLs:

.env
DATABASE_URL="your_database_url_here"
DIRECT_URL="your_direct_connection_string_here"

2.4.更新你的 Prisma 模式

¥2.4. Update your Prisma schema

打开 prisma/schema.prisma 并更新它以在 Bun 运行时使用驱动程序适配器:

¥Open prisma/schema.prisma and update it to use driver adapters with Bun runtime:

prisma/schema.prisma
generator client {
provider = "prisma-client-js"
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["driverAdapters", "queryCompiler"]
runtime = "bun"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}

3. 设置数据库配置并创建种子脚本

¥ Setting up database configuration and creating a seed script

3.1.创建数据库实用程序文件

¥3.1. Create a database utility file

在项目根目录中创建一个 db.ts 文件,以便使用 node-postgres 适配器配置 PrismaClient

¥Create a db.ts file in your project root to configure PrismaClient with the node-postgres adapter:

db.ts
import "dotenv/config";
import { PrismaClient } from "./generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";

const connectionString = `${process.env.DIRECT_URL}`;

const adapter = new PrismaPg({ connectionString });

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

3.2.创建种子脚本

¥3.2. Create a seed script

prisma 文件夹中创建一个种子脚本,用示例数据填充数据库:

¥Create a seed script in the prisma folder to populate your database with sample data:

prisma/seed.ts
import { PrismaClient } from "../generated/prisma/client";

const prisma = new PrismaClient();

async function main() {
// Create multiple users
await prisma.user.createMany({
data: [
{ email: "alice@example.com", name: "Alice" },
{ email: "bob@example.com", name: "Bob" },
{ email: "charlie@example.com", name: "Charlie" },
{ email: "diana@example.com", name: "Diana" },
{ email: "eve@example.com", name: "Eve" },
{ email: "frank@example.com", name: "Frank" },
{ email: "grace@example.com", name: "Grace" },
{ email: "henry@example.com", name: "Henry" },
{ email: "isabella@example.com", name: "Isabella" },
{ email: "jack@example.com", name: "Jack" },
],
skipDuplicates: true, // prevents errors if you run the seed multiple times
});

console.log("Seed data inserted!");
}

main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});

3.3.创建 Prisma 配置文件以运行种子脚本

¥3.3. Create Prisma Config file to run the seed script

创建一个 prisma.config.ts file 文件来配置 Prisma 的种子命令:

¥Create a prisma.config.ts file to configure Prisma's seed command:

touch prisma.config.ts

然后将以下内容添加到文件:

¥Then add the following content to the file:

prisma.config.ts
import 'dotenv/config'
import { defineConfig } from 'prisma/config'

export default defineConfig({
migrations: {
seed: `bun run prisma/seed.ts`,
},
})

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

¥ Generate Prisma client and run migrations

生成 Prisma 客户端并将你的架构应用于数据库:

¥Generate the Prisma client and apply your schema to the database:

bun prisma migrate dev --name init

这个命令:

¥This command:

  • 根据你的架构创建数据库表

    ¥Creates the database tables based on your schema

  • generated/prisma 目录中生成 Prisma 客户端

    ¥Generates the Prisma client in the generated/prisma directory

由于你正在使用 node-postgres 驱动程序适配器,因此需要重新生成 PrismaClientmigrate dev 自动生成的客户端已针对 Prisma Postgres 进行了优化,但适配器需要专门为驱动程序构建的客户端:

¥Because you are using the node-postgres driver adapter, you will need to generate the PrismaClient again. The client automatically produced by migrate dev is optimized for Prisma Postgres, but the adapter requires a client built specifically for the driver:

bun prisma generate

运行种子脚本,填充数据库:

¥Run the seed script to populate your database:

bun prisma db seed

5. 创建你的 Bun 服务器

¥ Creating your Bun server

index.ts 文件内容替换为以下代码,即可构建一个使用 Prisma ORM 获取并显示用户的简单 HTTP 服务器:

¥Replace the index.ts file contents with the following code to build a simple HTTP server that uses Prisma ORM to fetch and display users:

index.ts
import { prisma } from './db'

const server = Bun.serve({
port: 3000,
async fetch(req) {
const { pathname } = new URL(req.url)

// Skip favicon route
if (pathname === '/favicon.ico') {
return new Response(null, { status: 204 }) // or serve an icon if you have one
}

// Return all users
const users = await prisma.user.findMany()

// Count all users
const count = await prisma.user.count()

// Format the response with JSON
return new Response(
JSON.stringify({
users: users,
totalUsers: count,
}),
{ headers: { 'Content-Type': 'application/json' } },
)
},
})

console.log(`Listening on http://localhost:${server.port}`)

6. 运行你的应用

¥ Running your application

启动你的 Bun 服务器:

¥Start your Bun server:

bun run index.ts

你应该在控制台中看到 Listening on http://localhost:3000。在浏览器中访问 http://localhost:3000 时,你将看到一个 JSON 响应,其中包含数据库中的所有用户以及总数。

¥You should see Listening on http://localhost:3000 in the console. When you visit http://localhost:3000 in your browser, you'll see a JSON response with all the users in your database and the total count.

7. 构建并运行 Bun 可执行文件

¥ Building and running a Bun executable

Bun 可以编译你的 将 TypeScript 应用合并为单个可执行文件,这对于部署和分发非常有用。

¥Bun can compile your TypeScript application into a single executable file, which is useful for deployment and distribution.

7.1.构建可执行文件

¥7.1. Build the executable

将你的应用构建为可执行文件:

¥Build your application into an executable:

bun build --compile index.ts

这将在你的项目目录中创建一个名为 index(在 Windows 上为 index.exe)的可执行文件。

¥This creates an executable file named index (or index.exe on Windows) in your project directory.

7.2.运行可执行文件

¥7.2. Run the executable

运行已编译的可执行文件:

¥Run the compiled executable:

./index

你应该看到相同的 Listening on http://localhost:3000 消息,并且你的应用将与以前完全相同地工作。可执行文件包含所有依赖,无需安装 Bun 或 Node.js,即可部署到任何兼容系统。

¥You should see the same Listening on http://localhost:3000 message, and your application will work exactly the same as before. The executable includes all dependencies and can be deployed to any compatible system without requiring Bun or Node.js to be installed.

注意

Bun 可执行文件适用于:

¥Bun executables are useful for:

  • 部署:发布单个文件,而不是管理依赖

    ¥Deployment: Ship a single file instead of managing dependencies

  • 分发:共享你的应用,无需用户安装 Bun

    ¥Distribution: Share your application without requiring users to install Bun

  • 表现:与运行 TypeScript 文件相比,启动时间更快

    ¥Performance: Faster startup times compared to running TypeScript files

  • 安全性:你的源代码已编译,不易阅读。

    ¥Security: Your source code is compiled and not easily readable

下一步

¥Next steps

你可以按照本指南探索 示例应用,了解你将要构建的内容。如果你想为应用添加缓存,请查看 此示例

¥You can explore the sample app here to see what you will build by following this guide. If you would like to add caching to your application, check out this example.

现在,你已将 Bun 应用连接到 Prisma Postgres 数据库,你可以继续执行以下操作:

¥Now that you have a Bun application connected to a Prisma Postgres database, you can continue by:

  • 使用其他模型和关系扩展 Prisma 模式

    ¥Extending your Prisma schema with additional models and relationships

  • 实现身份验证和授权

    ¥Implementing authentication and authorization

  • 添加输入验证和错误处理

    ¥Adding input validation and error handling

  • 探索 Bun 的内置测试工具

    ¥Exploring Bun's built-in testing tools

  • 将可执行文件部署到生产服务器

    ¥Deploying your executable to production servers

更多信息

¥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!