如何将 Prisma ORM 和 Prisma Postgres 与 Nuxt 结合使用
本指南将向你展示如何在 Nuxt 应用中使用 Prisma Postgres 设置 Prisma ORM。
¥This guide shows you how to set up Prisma ORM in a Nuxt application with Prisma Postgres.
先决条件
¥Prerequisites
-
Node.js 18+
-
一个 数据库(或任何 PostgreSQL 数据库)
¥A database (or any PostgreSQL database)
1. 创建 Nuxt 项目
¥ Create a Nuxt project
创建一个新的 Nuxt 项目并安装依赖:
¥Create a new Nuxt project and install dependencies:
npx nuxi@latest init hello-prisma
cd hello-prisma
npm install @prisma/client @prisma/adapter-pg pg
npm install -D prisma @types/pg dotenv tsx
2. 初始化 Prisma
¥ Initialize Prisma
在项目中初始化 Prisma:
¥Initialize Prisma in your project:
npx prisma init
更新你的 prisma/schema.prisma:
¥Update your prisma/schema.prisma:
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?
}
在项目根目录中创建一个 prisma.config.ts 文件:
¥Create a prisma.config.ts file in the root of your project:
import { defineConfig, env } from 'prisma/config'
import 'dotenv/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx ./prisma/seed.ts',
},
datasource: {
url: env('DATABASE_URL'),
},
})
使用你的数据库连接字符串更新你的 .env 文件:
¥Update your .env file with your database connection string:
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
运行迁移以创建数据库表:
¥Run the migration to create your database tables:
npx prisma migrate dev --name init
3. 设置 Prisma 客户端
¥ Set up Prisma Client
创建 server/utils/db.ts。Nuxt 会自动从 server/utils 导入导出内容,使 prisma 在所有 API 路由中可用:
¥Create server/utils/db.ts. Nuxt auto-imports exports from server/utils, making prisma available in all API routes:
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../../prisma/generated/client'
const prismaClientSingleton = () => {
const pool = new PrismaPg({ connectionString: process.env.DATABASE_URL! })
return new PrismaClient({ adapter: pool })
}
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
4. 创建 API 路由
¥ Create API routes
创建用于获取用户的 API 路由。prisma 实例会自动导入:
¥Create an API route to fetch users. The prisma instance is auto-imported:
export default defineEventHandler(async () => {
const users = await prisma.user.findMany({
include: { posts: true }
})
return users
})
创建用于创建用户的 API 路由:
¥Create an API route to create a user:
export default defineEventHandler(async (event) => {
const body = await readBody<{ name: string; email: string }>(event)
const user = await prisma.user.create({
data: {
name: body.name,
email: body.email,
},
})
return user
})
5. 创建页面
¥ Create a page
更新 app.vue 以显示用户:
¥Update app.vue to display users:
<template>
<div>
<h1>Users</h1>
<ul v-if="users?.length">
<li v-for="user in users" :key="user.id">
{{ user.name }} ({{ user.email }})
</li>
</ul>
<p v-else>No users yet.</p>
</div>
</template>
<script setup>
const { data: users } = await useFetch('/api/users')
</script>
6. 运行应用
¥ Run the app
启动开发服务器:
¥Start the development server:
npm run dev
打开 http://localhost:3000 以查看你的应用。
¥Open http://localhost:3000 to see your app.
7. 为数据库填充种子(可选)
¥ Seed your database (optional)
创建一个种子用于填充数据库示例数据的文件:
¥Create a seed file to populate your database with sample data:
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 })
async function main() {
const alice = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World', published: true },
},
},
})
console.log(`Created user: ${alice.name}`)
}
main()
.then(() => prisma.$disconnect())
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
运行种子:
¥Run the seed:
npx prisma db seed
8. 部署到 Vercel
¥ Deploy to Vercel
你可以使用以下两种方法之一将 Nuxt 应用部署到 Vercel:
¥You can deploy your Nuxt application to Vercel using one of two methods:
选项 A:使用 Vercel CLI 部署
¥Option A: Deploy using Vercel CLI
-
安装 Vercel CLI(如果尚未安装):
¥Install the Vercel CLI (if not already installed):
npm install -g vercel -
部署项目:
¥Deploy your project:
npx vercel -
设置
DATABASE_URL环境变量:¥Set the
DATABASE_URLenvironment variable:-
前往你的 Vercel 仪表板
¥Go to your Vercel Dashboard
-
选择你的项目
¥Select your project
-
导航至“设置”→“环境变量”
¥Navigate to Settings → Environment Variables
-
添加包含数据库连接字符串的
DATABASE_URL¥Add
DATABASE_URLwith your database connection string
-
-
重新部署你的应用以应用环境变量:
¥Redeploy your application to apply the environment variable:
npx vercel --prod
选项 B:使用 Git 集成部署
¥Option B: Deploy using Git integration
-
将你的代码推送到 Git 仓库(GitHub、GitLab 或 Bitbucket)。
¥Push your code to a Git repository (GitHub, GitLab, or Bitbucket).
-
在
package.json的postinstall脚本中添加prisma generate,以确保在部署期间生成 Prisma Client:¥Add
prisma generateto yourpostinstallscript inpackage.jsonto ensure Prisma Client is generated during deployment:package.json{
"scripts": {
"postinstall": "prisma generate",
"build": "nuxt build",
"dev": "nuxt dev"
}
} -
将你的项目导入 Vercel:
¥Import your project in Vercel:
-
前往 Vercel 仪表板
¥Go to Vercel Dashboard
-
点击“添加新项目”→“项目”
¥Click Add New → Project
-
导入你的 Git 仓库
¥Import your Git repository
-
Vercel 会自动将其检测为 Nuxt 项目
¥Vercel will automatically detect it as a Nuxt project
-
-
配置环境变量:
¥Configure environment variables:
-
部署前,请前往“环境变量”页面
¥Before deploying, go to Environment Variables
-
添加包含数据库连接字符串的
DATABASE_URL¥Add
DATABASE_URLwith your database connection string -
点击部署
¥Click Deploy
-
Vercel 将自动构建和部署你的 Nuxt 应用。部署过程与其他 Node.js 应用相同,Prisma 客户端将在构建过程中由 postinstall 脚本生成。
¥Vercel will automatically build and deploy your Nuxt application. The deployment process is the same as any other Node.js application, and Prisma Client will be generated during the build process thanks to the postinstall script.
下一步
¥Next steps
-
探索 完整的 Nuxt + Prisma 集成示例,了解完整的博客应用
¥Explore the full Nuxt + Prisma example for a complete blog application
-
¥Learn about Prisma Client API
-
为托管数据库设置 Prisma Postgres
¥Set up Prisma Postgres for a managed database
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.