メインコンテンツへスキップ

REST

REST API を構築する際、Prisma Client はルートコントローラー内で使用され、データベースクエリを送信できます。

REST APIs with Prisma Client

サポートされているライブラリ

Prisma Client はデータベースへのクエリ送信のみを担うため、選択した任意の HTTP サーバーライブラリやウェブフレームワークと組み合わせることができます。

Prisma ORM で使用できるライブラリとフレームワークの非網羅的なリストを以下に示します

REST API サーバーの例

次のような Prisma スキーマがあると仮定します

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[]
}

これで、生成されたPrisma Client API を使用して、受信する HTTP リクエストが到着したときにデータベース操作を実行するルートコントローラー(例:Express を使用)を実装できます。このページにはいくつかのサンプルコードスニペットしか表示されていません。これらのコードスニペットを実行したい場合は、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エンドポイントはauthorオブジェクトを含むPostオブジェクトのネストされた JSON レスポンスを返すことに注意してください。以下にサンプルレスポンスを示します

[
{
"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 Client を使用して REST API を実装する方法や、完全なアプリケーションを構築する方法を示すすぐに実行できるいくつかのサンプルは、prisma-examples リポジトリにあります。

スタック説明
expressバックエンドのみTypeScript 用 Express を使用した 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)
© . All rights reserved.