跳到主要內容

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),當收到傳入的 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 以及構建完整的應用程式。

示例技術棧描述
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)
© . This site is unofficial and not affiliated with Prisma Data, Inc.