フルスタック
Next.js、Remix、SvelteKitなどのフルスタックフレームワークは、サーバーとクライアントの間の境界を曖昧にします。これらのフレームワークは、サーバー側でデータをフェッチおよび変更するための異なるパターンも提供します。
アプリケーションのサーバーサイド部分から、選択したフレームワークを使用してPrisma Clientでデータベースをクエリできます。
サポートされているフレームワーク
Prisma ORMで使用できるフレームワークとライブラリの非網羅的なリストを次に示します。
フルスタックアプリの例 (例: Next.js)
ヒント
Next.jsとPrisma ORMでアプリを構築する方法を学びたい場合は、この包括的なビデオチュートリアルをご覧ください。
次のような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[]
}
これで、getServerSideProps
、getStaticProps
、APIルート内、またはtRPCやGraphQLなどのAPIライブラリを使用して、Prisma Client APIでデータベースをクエリするロジックを実装できます。
getServerSideProps
// (in /pages/index.tsx)
// Alternatively, you can use `getStaticProps`
// in place of `getServerSideProps`.
export const getServerSideProps = async () => {
const feed = await prisma.post.findMany({
where: {
published: true,
},
})
return { props: { feed } }
}
Next.jsはpropsをReactコンポーネントに渡し、そこでデータベースからのデータを表示できます。
APIルート
// Fetch all posts (in /pages/api/posts.ts)
const prisma = new PrismaClient()
export default async function handle(req, res) {
const posts = await prisma.post.findMany({
where: {
published: true,
},
})
res.json(posts)
}
Next.js APIルート内でPrisma ORMを使用して、REST、GraphQL、tRPCでデータベースにクエリを送信できることに注意してください。
その後、データをフェッチしてフロントエンドに表示できます。
すぐに実行できるフルスタックのサンプルプロジェクト
prisma-examples
リポジトリには、Prisma Clientを使用したフルスタックアプリの構築方法を示すすぐに実行できるいくつかの例があります。
例 | 説明 |
---|---|
Next.js | フルスタック Next.js 15 アプリ |
Next.js (GraphQL) | GraphQL Yoga、Pothos、Apollo Clientを使用したフルスタック Next.js アプリ |
Remix | アクションとローダーを使用したフルスタック Remix アプリ |
SvelteKit | アクションとローダーを使用したフルスタック Sveltekit アプリ |
Nuxt | APIルートを使用したフルスタック Nuxt アプリ |