1
1

マッチングアプリを作るときにTypeScriptとPythonのFlaskが重宝する理由

Last updated at Posted at 2024-08-03

TypeScriptを使ってマッチングアプリを作る!

こんにちは!今回は、TypeScriptとFlaskを使ってマッチングアプリを作成する方法をご紹介します。このガイドでは、フロントエンドにTypeScript、バックエンドにFlaskを使用し、step by stepで開発プロセスを説明していきます。

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

まず、プロジェクトの基本構造を作成しましょう。

matching-app/
├── frontend/
│   ├── src/
│   ├── public/
│   ├── package.json
│   └── tsconfig.json
└── backend/
    ├── app.py
    ├── requirements.txt
    └── venv/

フロントエンドのセットアップ

フロントエンドではReactとTypeScriptを使用します。

npx create-react-app frontend --template typescript
cd frontend
npm install axios

バックエンドのセットアップ

バックエンドではFlaskを使用します。

cd backend
python -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`
pip install flask flask-cors
pip freeze > requirements.txt

2. バックエンドの開発

app.pyにFlaskアプリケーションを作成します。

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

users = [
    {"id": 1, "name": "田中太郎", "age": 25, "interests": ["読書", "旅行"]},
    {"id": 2, "name": "佐藤花子", "age": 28, "interests": ["料理", "スポーツ"]},
    # ... more users ...
]

@app.route('/api/users', methods=['GET'])
def get_users():
    return jsonify(users)

@app.route('/api/match', methods=['POST'])
def match_users():
    user_id = request.json['userId']
    user = next((u for u in users if u['id'] == user_id), None)
    if not user:
        return jsonify({"error": "User not found"}), 404
    
    matches = [u for u in users if u['id'] != user_id and set(u['interests']) & set(user['interests'])]
    return jsonify(matches)

if __name__ == '__main__':
    app.run(debug=True)

3. フロントエンドの開発

3.1 ユーザー一覧コンポーネント

src/components/UserList.tsxを作成します。

import React, { useEffect, useState } from 'react';
import axios from 'axios';

interface User {
  id: number;
  name: string;
  age: number;
  interests: string[];
}

const UserList: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);

  useEffect(() => {
    const fetchUsers = async () => {
      const response = await axios.get('http://localhost:5000/api/users');
      setUsers(response.data);
    };
    fetchUsers();
  }, []);

  return (
    <div>
      <h2>ユーザー一覧</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} ({user.age}) - 興味: {user.interests.join(', ')}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;

3.2 マッチング機能コンポーネント

src/components/Matching.tsxを作成します。

import React, { useState } from 'react';
import axios from 'axios';

interface User {
  id: number;
  name: string;
  age: number;
  interests: string[];
}

const Matching: React.FC = () => {
  const [userId, setUserId] = useState<number>(0);
  const [matches, setMatches] = useState<User[]>([]);

  const handleMatch = async () => {
    try {
      const response = await axios.post('http://localhost:5000/api/match', { userId });
      setMatches(response.data);
    } catch (error) {
      console.error('Matching error:', error);
    }
  };

  return (
    <div>
      <h2>マッチング</h2>
      <input
        type="number"
        value={userId}
        onChange={(e) => setUserId(Number(e.target.value))}
        placeholder="ユーザーID"
      />
      <button onClick={handleMatch}>マッチングを開始</button>
      <h3>マッチング結果:</h3>
      <ul>
        {matches.map(user => (
          <li key={user.id}>
            {user.name} ({user.age}) - 興味: {user.interests.join(', ')}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Matching;

3.3 メインアプリケーションコンポーネント

src/App.tsxを更新します。

import React from 'react';
import UserList from './components/UserList';
import Matching from './components/Matching';

const App: React.FC = () => {
  return (
    <div className="App">
      <h1>マッチングアプリ</h1>
      <UserList />
      <Matching />
    </div>
  );
};

export default App;

4. アプリケーションの実行

  1. バックエンドの起動:
cd backend
source venv/bin/activate  # On Windows use `venv\Scripts\activate`
python app.py
  1. フロントエンドの起動:
cd frontend
npm start

ブラウザでhttp://localhost:3000を開くと、アプリケーションが表示されます。

5. まとめ

このチュートリアルでは、TypeScriptとFlaskを使用してシンプルなマッチングアプリケーションを作成しました。フロントエンドではReactとTypeScriptを使用してユーザーインターフェースを構築し、バックエンドではFlaskを使用してAPIを提供しました。

このアプリケーションをベースに、さらに機能を追加したり、デザインを改善したりすることができます。例えば、ユーザー認証、プロフィール編集、リアルタイムチャット機能などを追加することで、より本格的なマッチングアプリケーションに発展させることができるでしょう。

TypeScriptとFlaskの組み合わせは、フロントエンドとバックエンドの両方で型安全性を確保しつつ、高速な開発を可能にします。この組み合わせを使いこなすことで、効率的で堅牢なウェブアプリケーションを開発することができます。

ぜひ、このプロジェクトをベースに、自分だけのユニークなマッチングアプリを作成してみてください。がんばってください!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1