跳到主要内容

REST

当构建 REST API 时,Prisma Client 可以在你的 路由控制器 中使用,以发送数据库查询。

REST APIs with Prisma Client

支持的库

由于 Prisma Client “仅” 负责向你的数据库发送查询,因此它可以与你选择的任何 HTTP 服务器库或 Web 框架结合使用。

以下是你可以与 Prisma ORM 一起使用的库和框架的非详尽列表

REST API 服务器示例

假设你有一个 Prisma schema,看起来和这个类似

datasource db {
provider = "sqlite"
url = "file:./dev.db"
}

generator client {
provider = "prisma-client-js"
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}

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

你现在可以实现路由控制器(例如,使用 Express),它使用生成的 Prisma Client API 在传入 HTTP 请求到达时执行数据库操作。此页面仅显示少量代码片段示例;如果你想运行这些代码片段,你可以使用 REST API 示例

GET

app.get('/feed', async (req, res) => {
const posts = await prisma.post.findMany({
where: { published: true },
include: { author: true },
})
res.json(posts)
})

请注意,在这种情况下,feed 端点返回 Post 对象的嵌套 JSON 响应,其中 *包含* author 对象。这是一个示例响应

[
{
"id": "21",
"title": "Hello World",
"content": "null",
"published": "true",
"authorId": 42,
"author": {
"id": "42",
"name": "Alice",
"email": "[email protected]"
}
}
]

POST

app.post(`/post`, async (req, res) => {
const { title, content, authorEmail } = req.body
const result = await prisma.post.create({
data: {
title,
content,
published: false,
author: { connect: { email: authorEmail } },
},
})
res.json(result)
})

PUT

app.put('/publish/:id', async (req, res) => {
const { id } = req.params
const post = await prisma.post.update({
where: { id: Number(id) },
data: { published: true },
})
res.json(post)
})

DELETE

app.delete(`/post/:id`, async (req, res) => {
const { id } = req.params
const post = await prisma.post.delete({
where: {
id: Number(id),
},
})
res.json(post)
})

即用型示例项目

你可以在 prisma-examples 仓库中找到几个即用型示例,展示了如何使用 Prisma Client 实现 REST API,以及构建完整的应用程序。

示例技术栈描述
express仅后端使用 Express 和 TypeScript 的 REST API
fastify仅后端使用 Fastify 和 Prisma Client 的 REST API。
hapi仅后端使用 hapi 和 Prisma Client 的 REST API
nestjs仅后端使用 REST API 的 Nest.js 应用 (Express)
nextjs全栈使用 REST API 的 Next.js 应用 (React)