5. Next.js でチャットボット - 2

データモデル

データモデルとは

データモデルはデータ構造を定義し、データ管理するための概念です。データベース設計やシステム開発において、データの整合性や効率的なデータアクセスするために重要な設計です。モデルファイルを定義しておくことで、プログラムの効率化やバグを防ぎやすくなります。

TypeScriptの利用

TypeScriptには、データの形状を定義するために「インターフェース (interface)」と「型エイリアス (type)」があります。

Interface
interface User {
  id: number;
  name: string;
  email: string;
  isActive?: boolean; // optional property
}

const user: User = {
  id: 1,
  name: "John Doe",
  email: "[email protected]"
};
Type
type User = {
  id: number;
  name: string;
  email: string;
  isActive?: boolean; // optional property
};

const user: User = {
  id: 1,
  name: "John Doe",
  email: "[email protected]"
};

Roleファイル作成

メッセージの権限を設定する app/constants/roles.ts ファイルを作成します。このファイルは、role に対する表示ラベルとスタイルをまとめた設定です。

export const ROLE_USER = 'user' as const;
export const ROLE_BOT = 'bot' as const;
export type Role = typeof ROLE_USER | typeof ROLE_BOT;

export const roleConfig: Record<
    Role,
    { label: string; bubbleClass: string; tagClass: string }
> = {
    [ROLE_USER]: {
        label: 'あなた',
        bubbleClass: 'bg-blue-100 text-blue-800',
        tagClass: 'bg-blue-600',
    },
    [ROLE_BOT]: {
        label: 'Bot',
        bubbleClass: 'bg-gray-100 text-gray-800',
        tagClass: 'bg-gray-600',
    },
};

インターフェイス

Message インターフェイス app/interfaces/Message.ts を作成します。

インターフェイス定義

roles をインポートし、content, role を定義します。

app/interface/Message.ts
import type { Role } from '@/app/constants/roles';

export interface Message {
    content: string;
    role?: Role;
}
  • 「content」は string型
  • 「role」は「user」「bot」の2種類の Role型

バックエンドAPI作成

Next.jsをバックエンドとして、POSTリクエストに対応したAPIを作成します。

仕様

項目 エンドポイント HTTPメソッド JSON
チャット送受信 /api/chat/ POST { message: Message}
  1. Next.js APIサーバに、メッセージをPOSTリクエスト
  2. Gemini APIにメッセージをリクエスト
  3. Gemini APIのレスポンスデータ取得
  4. Next.js APIサーバがデータをレスポンス

ファイル構成

./
├── app/
│   ├── api/
│   │   └── chat/
│   │           └── route.ts
│   ├── interfaces/Message.ts
│   ├── constants/role.ts

Next.js API作成

ファイル作成

ルーティングファイル app/api/chat/route.ts を作成します。

POSTリクエスト

POSTリクエストAPIを作成します。

app/api/chat/route.ts
import { NextRequest } from 'next/server';

export async function POST(req: NextRequest) {
    
}

POSTデータの message を非同期取得し、コンソール表示します。

app/api/chat/route.ts
import { NextRequest } from 'next/server';

export async function POST(req: NextRequest) {
    // POSTデータ取得
    const message = await req.json();
    if (!message) return NextResponse.json({ error: "Not found message" });
    console.log('Received message:', message);
}

レスポンス

固定のボットメッセージをレスポンスします。

app/api/chat/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { ROLE_BOT } from '@/app/constants/roles';

export async function POST(req: NextRequest) {
    const message = await req.json();
    if (!message) return NextResponse.json({ error: "Not found message" });
    console.log('Received message:', message);
    const botMessage = "Botのメッセージ";
    return NextResponse.json({ content: botMessage, role: ROLE_BOT });
}