跳至主要內容

如何在 Bun 中使用 Prisma

10 分鐘

簡介

Bun 是一個快速的 JavaScript 執行環境,包含打包工具、測試執行器和套件管理器。在本指南中,您將使用 Prisma ORM 和 Prisma Postgres 資料庫建立一個 Bun 專案。您將建立一個簡單的 HTTP 伺服器,並建構一個用於部署的 Bun 可執行檔。

先決條件

1. 設定您的 Bun 專案

首先,為您的專案建立一個目錄並進入該目錄

mkdir bun-prisma
cd bun-prisma

接著,初始化一個新的 Bun 專案

bun init -y

這將建立一個包含 package.json 檔案和 index.ts 檔案的基本 Bun 專案。

2. 安裝與設定 Prisma

2.1. 安裝依賴項目

安裝必要的 Prisma 套件與其他依賴項

bun add -d prisma @types/pg
bun add @prisma/client @prisma/adapter-pg pg
資訊

如果您使用的是不同的資料庫提供者(MySQL、SQL Server、SQLite),請安裝相應的驅動程式適配器套件,而不是 @prisma/adapter-pg。如需更多資訊,請參閱資料庫驅動程式

2.2. 使用 Prisma Postgres 初始化 Prisma ORM

在您的專案中使用 Prisma Postgres 初始化 Prisma ORM

bun prisma init --db
資訊

設定 Prisma Postgres 資料庫時,您需要回答幾個問題。請選擇離您最近的區域,並為您的資料庫取一個易於記憶的名稱,例如「My Bun Project」。

此指令會建立:

  • 一個包含 schema.prisma 檔案的 prisma/ 目錄
  • 一個新的 Prisma Postgres 資料庫
  • 一個 prisma.config.ts 檔案
  • 一個包含 DATABASE_URL.env 檔案

2.3. 設定直接連線的環境變數

我們將使用直接連線字串來連線至 Prisma Postgres。若要取得您的直接連線字串

  1. 前往您剛建立的 Prisma Postgres 專案儀表板(例如「My Bun Project」)
  2. 點選專案側邊欄中的 **API Keys** 分頁
  3. 點選 **Create API key** 按鈕
  4. 為 API 金鑰命名並點選 **Create**
  5. 複製以 postgres:// 開頭的連線字串

更新您的 .env 檔案,將 DATABASE_URL 替換為新的連線字串

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

2.4. 更新您的 Prisma Schema

開啟 prisma/schema.prisma 並更新它以包含您的資料模型

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

datasource db {
provider = "postgresql"
}

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

3. 產生 Prisma Client 並執行遷移

產生 Prisma client 並將您的 schema 套用到資料庫

bunx --bun prisma migrate dev --name init
bunx --bun prisma generate

此命令會

  • 根據您的 schema 建立資料庫表格
  • generated/prisma 目錄中產生 Prisma client

4. 設定資料庫組態與建立種子 (Seed) 腳本

4.1. 建立資料庫公用程式檔案

在您的專案根目錄中建立 db.ts 檔案以設定 PrismaClient

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

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

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

4.2. 建立種子 (Seed) 腳本

prisma 資料夾中建立種子腳本,以使用範例資料填充您的資料庫

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

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

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

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 Config

將以下內容新增至檔案中

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

export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: `bun run prisma/seed.ts`
},
datasource: {
url: env('DATABASE_URL'),
},
});

執行種子腳本以填充您的資料庫

bunx --bun prisma db seed

5. 建立您的 Bun 伺服器

index.ts 檔案內容替換為以下程式碼,以建立一個簡單的 HTTP 伺服器,使用 Prisma ORM 來獲取並顯示使用者

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 https://:${server.port}`)

6. 執行您的應用程式

啟動您的 Bun 伺服器

bun run index.ts

您應該會在控制台中看到 Listening on https://:3000。當您在瀏覽器中造訪 https://:3000 時,您將看到一個 JSON 回應,其中包含資料庫中的所有使用者及其總計數量。

7. 建構並執行 Bun 可執行檔

Bun 可以將您的 TypeScript 應用程式編譯成單一的可執行檔,這對於部署和分發非常有用。

7.1. 建構可執行檔

將您的應用程式建構為可執行檔

bun build --compile index.ts

這將在您的專案目錄中建立一個名為 index(在 Windows 上為 index.exe)的可執行檔。

7.2. 執行可執行檔

執行已編譯的可執行檔

./index

您應該會看到相同的 Listening on https://:3000 訊息,且您的應用程式運作方式將與之前完全相同。該可執行檔包含了所有依賴項,無需安裝 Bun 或 Node.js 即可部署到任何相容系統。

注意

Bun 可執行檔的優點:

  • 部署:只需發布單一檔案,無需管理依賴項
  • 分發:分享您的應用程式,無需使用者安裝 Bun
  • 效能:與執行 TypeScript 檔案相比,啟動速度更快
  • 安全性:您的原始碼已編譯,不容易被讀取

後續步驟

您可以探索 此範例 以查看使用 Bun 和 Prisma 構建的範例應用程式。

現在您已經有一個連線至 Prisma Postgres 資料庫的 Bun 應用程式,您可以透過以下方式繼續:

  • 使用額外的模型和關聯擴充您的 Prisma schema
  • 實作身份驗證與授權
  • 新增輸入驗證與錯誤處理
  • 探索 Bun 內建的測試工具
  • 將您的可執行檔部署到生產伺服器

更多資訊


與 Prisma 保持聯繫

透過以下方式與我們聯繫,繼續您的 Prisma 旅程: 我們的活躍社群。保持資訊靈通、參與其中,並與其他開發者合作

我們衷心感謝您的參與,並期待您成為我們社群的一份子!

© . This site is unofficial and not affiliated with Prisma Data, Inc.