如何將 Prisma ORM 與 Nuxt 搭配使用
本指南說明如何設定 Nuxt 應用程式、使用 Prisma ORM 設定 Prisma Postgres,並將專案部署至 Vercel 以進行生產環境部署。
您將學到以下內容
- 如何設定一個直接使用 Prisma ORM 的 Nuxt 專案。
- 如何在 Nuxt 應用程式中設定並使用 Prisma Postgres 與 Prisma ORM。
- 如何將專案部署至 Vercel。
先決條件
若要遵循本指南,請確保您已具備以下條件
- Node.js 版本:Prisma 6 所需的相容 Node.js 版本。
- 帳戶
- 對 Git 和 Vercel 部署有基本了解(有幫助但非必要)。
1. 建立新的 Nuxt 專案並安裝 Prisma ORM 依賴項
- 初始化一個新的 Nuxt 專案,選擇
npm作為套件管理員,並初始化 gitnpm create nuxt hello-world - 進入專案目錄,並安裝 Prisma ORM 依賴項以及 PostgreSQL 驅動程式配接器
cd hello-world
npm install @prisma/client @prisma/adapter-pg pg dotenv tsx
npm install -D prisma @types/pg - 透過執行以下指令,使用 PostgreSQL 初始化 Prisma
npx prisma init --db
2. 設定 Prisma
在執行開發伺服器之前,請在專案根目錄中建立一個 prisma.config.ts 檔案,以管理環境變數與設定
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx ./prisma/seed.ts',
},
datasource: {
url: env('DATABASE_URL'),
},
})
3. 設定 Prisma ORM
在初始化 Prisma 後,定義您的資料模型並執行遷移 (migration) 以建立 PostgreSQL 資料庫。
- 使用以下設定更新
prisma/schema.prisma檔案prisma/schema.prisma// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client"
output = "./generated"
}
datasource db {
provider = "postgresql"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
} - 建立初始遷移並建立資料庫資料表
npx prisma migrate dev --name init - 指令成功執行後,啟動 Nuxt 開發伺服器
npm run dev - 當伺服器於
https://:3000執行時,請先將其停止——我們在繼續之前需要更新一些檔案。
4. 更新應用程式程式碼
在設定好 Prisma 後,下一步是更新您的應用程式程式碼,以從資料庫取得並顯示資料。
-
在專案根目錄中建立一個名為
lib的資料夾,並新增一個prisma.ts檔案,以共用透過 PostgreSQL 配接器連接的單一 Prisma Client 實例lib/prisma.tsimport { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../prisma/generated/client'
const prismaClientSingleton = () => {
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! })
return new PrismaClient({ adapter })
}
type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClientSingleton | undefined
}
export const prisma = globalForPrisma.prisma ?? prismaClientSingleton()
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma -
建立一個名為
components的資料夾(如果尚未存在),並在其中新增User.server.vue。此伺服器元件會從資料庫取得並顯示第一位使用者的姓名components/User.server.vue<script setup>
import prisma from '~/lib/prisma'
const user = await prisma.user.findFirst()
</script>
<template>
<p>{{ user?.name ?? "No user has been added yet." }}</p>
</template> -
修改根目錄中的
app.vue檔案,使用 Nuxt Islands 引入新的伺服器元件app.vue<template>
<div>
<NuxtIsland name="User"></NuxtIsland>
</div>
</template> -
執行以下指令再次啟動開發伺服器
npm run dev -
在瀏覽器開啟
https://:3000以確認應用程式程式碼運作正常。
由於目前資料庫中沒有使用者,應用程式將顯示No user has been added yet.當您將使用者新增至資料庫時,此訊息將會動態更新。
完成這些步驟後,您的應用程式現在能夠從 Prisma 資料庫取得資料並在前端進行渲染。
5. 為資料庫填充種子資料(選用)
如果您需要範例資料,請建立一個 prisma/seed.ts 檔案。以下指令碼使用了 PostgreSQL 配接器
import 'dotenv/config'
import { PrismaClient } from './generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! })
const prisma = new PrismaClient({ adapter })
const userData = [
{
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: [
{
title: 'Join the Prisma Discord',
content: 'https://pris.ly/discord',
published: true,
},
],
},
},
{
name: 'Nilu',
email: 'nilu@prisma.io',
posts: {
create: [
{
title: 'Follow Prisma on Twitter',
content: 'https://www.twitter.com/prisma',
published: true,
},
],
},
},
{
name: 'Mahmoud',
email: 'mahmoud@prisma.io',
posts: {
create: [
{
title: 'Ask a question about Prisma on GitHub',
content: 'https://www.github.com/prisma/prisma/discussions',
published: true,
},
{
title: 'Prisma on YouTube',
content: 'https://pris.ly/youtube',
},
],
},
},
]
async function main() {
console.log(`Start seeding ...`)
for (const u of userData) {
const user = await prisma.user.create({
data: u,
})
console.log(`Created user with id: ${user.id}`)
}
console.log(`Seeding finished.`)
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
當您需要展示資料時,執行填充種子指令
npx prisma db seed
6. 建立 Prisma Postgres 實例
若要儲存應用程式的資料,您將使用 Prisma Data Platform 建立一個 Prisma Postgres 資料庫實例。
請依照下列步驟建立您的 Prisma Postgres 資料庫
- 登入並開啟主控台 (Console)。
- 在您選擇的 工作區 (workspace) 中,點擊 New project (新增專案) 按鈕。
- 在 Name (名稱) 欄位中輸入您的專案名稱,例如 hello-ppg。
- 在 Prisma Postgres 區段中,點擊 Get started (開始使用) 按鈕。
- 在 Region (區域) 下拉選單中,選擇離您目前位置最近的區域,例如 US East (N. Virginia)。
- 點擊 Create project (建立專案) 按鈕。
此時,您將被重新導向至資料庫 (Database) 頁面,需等待幾秒鐘,直到資料庫狀態從 PROVISIONING 變更為 CONNECTED。
當綠色的 CONNECTED 標籤出現時,代表資料庫已準備就緒!
接著,在 設定資料庫存取 (Set up database access) 區段中找到您的資料庫憑證,並複製 DATABASE_URL 環境變數。
DATABASE_URL=<your-database-url>
DATABASE_URL 環境變數將在後續步驟中使用。
7. 在 Nuxt 應用程式中設定 Prisma Postgres
現在 Prisma Postgres 實例已準備好,請更新您的 Nuxt 應用程式以使用此資料庫
-
更新
.env檔案,將現有的DATABASE_URL值替換為您先前複製的值。它看起來會像這樣.envDATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=PRISMA_POSTGRES_API_KEY" -
手動執行遷移以將您的架構 (schema) 同步至 Prisma Postgres
npx prisma migrate dev --name init -
(選用)使用範例資料填充您的資料庫
npx prisma db seed -
再次啟動開發伺服器
npm run dev -
在瀏覽器開啟
https://:3000以驗證應用程式中的資料。如果您已填充種子資料,您應該會看到第一位使用者的姓名。
恭喜,您的 Nuxt 應用程式現已完全整合 Prisma Postgres!
8. 部署至 Vercel
按照以下步驟,將整合了 Prisma Postgres 的 Nuxt 應用程式部署至 Vercel
- 確保您的專案已進行版本控制並推送至 GitHub 儲存庫。如果您尚未建立儲存庫,請在 GitHub 上建立一個。一旦儲存庫準備就緒,請執行以下指令
git add .
git commit -m "Initial commit with Prisma Postgres integration"
git branch -M main
git remote add origin https://github.com/<your-username>/<repository-name>.git
git push -u origin main注意將
<your-username>和<repository-name>取代為您的 GitHub 使用者名稱與儲存庫名稱。 - 登入 Vercel 並前往您的 儀表板 (Dashboard)。
- 建立一個新專案。遵循 Vercel 的 匯入現有專案 指南,但在步驟 3 停下來,在點擊 部署 (Deploy) 之前設定環境變數。
- 設定
DATABASE_URL環境變數- 展開 環境變數 (Environment variables) 區段。
- 新增
DATABASE_URL環境變數- 鍵 (Key):
DATABASE_URL - 值 (Value): 貼上您的 Prisma Postgres 連接 URL,例如從您 Nuxt 專案的
.env檔案中複製。
警告請勿在未設定
DATABASE_URL變數的情況下部署。如果應用程式無法連接至資料庫,您的部署將會失敗。 - 鍵 (Key):
- 點擊 部署 (Deploy) 按鈕。Vercel 將會建構您的專案並將其部署至一個公開 URL。
- 開啟 Vercel 提供的公開 URL,確認您的應用程式運作正常
- 如果您已在 Prisma Studio 新增使用者,他們的姓名應該會出現在即時網站上。
- 如果沒有使用者,應用程式將顯示
No user has been added yet.
- 若要新增或管理資料
- 透過 Prisma Data Platform 或本機實例開啟 Prisma Studio。
- 在資料庫中新增或更新使用者資料。
- 重新整理您的即時網站以確認變更。
恭喜!您使用 Prisma Postgres 整合的 Nuxt 應用程式現已上線並完全正常運作。
考量事項
本指南協助您開始在 Nuxt 應用程式中使用 Prisma Postgres。如需更進階的功能或邊緣部署 (edge deployments),請探索 Prisma 的更多指南,並根據專案需求進行調整。
與 Prisma 保持聯繫
透過以下方式與我們聯繫,繼續您的 Prisma 旅程: 我們的活躍社群。保持資訊靈通、參與其中,並與其他開發者合作
- 在 X 上關注我們 以獲取公告、現場活動和實用技巧。
- 加入我們的 Discord 提出問題、與社群對話,並透過對話獲得積極支援。
- 在 YouTube 上訂閱 查看教學、演示和直播。
- 在 GitHub 上交流 透過為存放庫加星標、報告問題或為 issue 做出貢獻。