REST
在构建 REST API 时,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),当收到传入的 HTTP 请求时,它使用生成的 Prisma Client API 来执行数据库操作。本页只展示了一些代码片段示例;如果你想运行这些代码片段,可以使用一个 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
端点返回一个嵌套的 JSON 响应,其中包含的 Post
对象 包含 一个 author
对象。以下是一个示例响应
[
{
"id": "21",
"title": "Hello World",
"content": "null",
"published": "true",
"authorId": 42,
"author": {
"id": "42",
"name": "Alice",
"email": "alice@prisma.io"
}
}
]
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 以及构建完整的应用程序。