跳至主要內容

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": "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僅後端適用於 TypeScript 的 Express REST API
fastify僅後端使用 Fastify 和 Prisma Client 的 REST API。
hapi僅後端使用 hapi 和 Prisma Client 的 REST API
nestjs僅後端具有 REST API 的 Nest.js 應用程式 (Express)
nextjsFullstack具有 REST API 的 Next.js 應用程式 (React)