メインコンテンツへスキップ
ブログ一覧に戻る
バックエンド開発

PrismaとSupabaseを使ったバックエンド構築の基礎

2023年12月10日
10分で読めます
PrismaとSupabaseを使ったバックエンド構築の基礎

この記事の結論

モダンなバックエンド開発においてPrisma ORMとSupabaseを活用したデータベース設計と実装方法について解説します。

PrismaとSupabaseを使ったバックエンド構築の基礎

モダンなバックエンド開発においてPrisma ORMとSupabaseを活用したデータベース設計と実装方法について解説します。

はじめに

PrismaとSupabaseの組み合わせは、モダンなバックエンド開発において非常に強力です。Prismaは型安全なORMを提供し、SupabaseはPostgreSQLベースのBaaS(Backend as a Service)を提供します。本記事では、これらのツールを活用して、効率的で保守性の高いバックエンドを構築する方法を解説します。

Prismaとは

Prismaは、データベースへのアクセスを簡素化するORM(Object-Relational Mapping)ツールです。主な特徴は以下の通りです:

  • 型安全性: TypeScriptと完全に統合され、コンパイル時に型チェックが可能
  • マイグレーション: データベーススキーマの変更をバージョン管理
  • クエリビルダー: 直感的なAPIでデータベースクエリを構築

Supabaseとは

Supabaseは、オープンソースのFirebase代替として開発されたBaaSプラットフォームです。主な機能は以下の通りです:

  • PostgreSQLデータベース: フル機能のPostgreSQLデータベースを提供
  • リアルタイム機能: WebSocketを使用したリアルタイムデータ同期
  • 認証: ユーザー認証機能を内蔵
  • ストレージ: ファイルストレージ機能

PrismaとSupabaseの統合

セットアップ

まず、Prismaをプロジェクトに追加します:

npm install prisma @prisma/client
npx prisma init

次に、schema.prismaファイルを設定します:

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        String   @id @default(uuid())
  email     String   @unique
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model Post {
  id        String   @id @default(uuid())
  title     String
  content   String?
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

データベース接続

SupabaseのデータベースURLを環境変数に設定します:

DATABASE_URL="postgresql://user:password@host:5432/database?schema=public"

マイグレーション

Prismaを使用してデータベーススキーマをマイグレーションします:

npx prisma migrate dev --name init

実践的な例

ユーザー作成

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function createUser(email: string, name: string) {
  const user = await prisma.user.create({
    data: {
      email,
      name,
    },
  })
  return user
}

投稿の作成と取得

async function createPost(title: string, content: string, authorId: string) {
  const post = await prisma.post.create({
    data: {
      title,
      content,
      authorId,
      published: true,
    },
    include: {
      author: true,
    },
  })
  return post
}

async function getPosts() {
  const posts = await prisma.post.findMany({
    where: {
      published: true,
    },
    include: {
      author: true,
    },
    orderBy: {
      createdAt: 'desc',
    },
  })
  return posts
}

Prisma×Supabaseでバックエンドを構築する要点

PrismaとSupabaseを組み合わせることで、型安全で効率的なバックエンドを構築できます。Prismaの型安全性とSupabaseの豊富な機能を活用することで、開発速度と保守性の両方を向上させることができます。

関連記事


ご相談・お問い合わせはこちら

次の一手

状況に合わせて、選んでください。