astroでcrudを実装する

Astroでカウントアップ機能を実装する

Astroは、静的サイト生成(SSG)とサーバーサイドレンダリング(SSR)に対応したモダンなウェブフレームワークです。React、Vue、Svelte、Solidなどのさまざまなフレームワークと統合できる特徴を持ち、特にパフォーマンスに優れたウェブサイトを構築するのに適しています。本記事では、AstroとPrismaを組み合わせたカウントアップ機能の実装方法について説明します。

1. プロジェクトのセットアップ

Astroをプロジェクトに導入するには、以下の手順を実行します。

npm create astro@latest
cd my-astro-counter
npm install
npm install @prisma/client prisma

2. Prismaのセットアップ

Prismaを初期化し、データベーススキーマを定義します。

npx prisma init

次に、prisma/schema.prisma を編集してデータモデルを定義します。

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

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

model Counter {
  id    Int    @id @default(autoincrement())
  count Int    @default(0)
}

マイグレーションを実行し、データベースを作成します。

npx prisma migrate dev --name init

3. カウントアップAPIの実装

src/pages/api/counter.ts を作成し、カウント値を取得・更新できるAPIを実装します。

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function GET() {
  let counter = await prisma.counter.findFirst();
  if (!counter) {
    counter = await prisma.counter.create({ data: { count: 0 } });
  }
  return new Response(JSON.stringify(counter), {
    headers: { "Content-Type": "application/json" },
  });
}

export async function POST() {
  const counter = await prisma.counter.findFirst();
  if (!counter) {
    return new Response("Counter not found", { status: 404 });
  }
  const updatedCounter = await prisma.counter.update({
    where: { id: counter.id },
    data: { count: counter.count + 1 },
  });
  return new Response(JSON.stringify(updatedCounter), {
    headers: { "Content-Type": "application/json" },
  });
}

4. フロントエンドの実装

Astroのコンポーネントを使用してカウントを表示し、ボタンを押すとカウントアップできるようにします。

src/pages/index.astro

---
import { useState, useEffect } from 'react';

const [count, setCount] = useState(0);

useEffect(() => {
  fetch('/api/counter')
    .then(response => response.json())
    .then(data => setCount(data.count));
}, []);

const handleIncrement = async () => {
  const response = await fetch('/api/counter', { method: 'POST' });
  const data = await response.json();
  setCount(data.count);
};
---

<html>
  <head>
    <title>Astro Counter with Prisma</title>
  </head>
  <body>
    <h1>Counter</h1>
    <p>Count: {count}</p>
    <button onClick={handleIncrement}>Increment</button>
  </body>
</html>

まとめ

AstroとPrismaを使用して、カウントアップ機能を構築する方法を紹介しました。APIルートを利用することで、データベースとフロントエンドが連携し、ボタンを押すたびにカウントが更新される仕組みになっています。