バックエンドのアプリケーションでは、クライアントからのリクエストを受け取り、データベースとやり取りし、適切なレスポンスを返します。本記事では、データの流れを詳細に説明し、それぞれのフォルダーの役割を明確にします!💡
📌 データの流れと各フォルダーの役割
📌 ユーザー情報を取得するリクエスト (GET /users/:id) の流れ
1️⃣ ルート(routes/)
- クライアント(ブラウザやAPIクライアント)からのリクエストを受け取り、適切なコントローラーを指定。
-
例:
userRoutes.jsでGET /users/:idをuserController.getUserにルーティング。
✅ コード例(routes/userRoutes.js)
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const authMiddleware = require('../middlewares/authMiddleware');
router.get('/users/:id', authMiddleware, userController.getUser);
module.exports = router;
2️⃣ コントローラー(controllers/)
- ルートからリクエストを受け取り、適切なサービスを呼び出す。
-
例:
userController.jsでgetUser(req, res)を定義し、userService.getUserById(req.params.id)を実行。
✅ コード例(controllers/userController.js)
const userService = require('../services/userService');
exports.getUser = async (req, res) => {
try {
const user = await userService.getUserById(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(500).json({ message: 'Internal Server Error' });
}
};
3️⃣ サービス(services/)
- リポジトリからデータを取得し、ビジネスロジックを適用。
-
例:
userService.jsでgetUserById(id)を定義し、userRepository.findById(id)を呼び出す。
✅ コード例(services/userService.js)
const userRepository = require('../repositories/userRepository');
exports.getUserById = async (id) => {
return await userRepository.findById(id);
};
4️⃣ リポジトリ(repositories/)
- モデルを使ってデータベースからデータを取得。
-
例:
userRepository.jsでfindById(id)を定義し、User.findById(id)を実行。
✅ コード例(repositories/userRepository.js)
const User = require('../models/User');
exports.findById = async (id) => {
return await User.findById(id);
};
5️⃣ モデル(models/)
- データベースのスキーマを定義。
-
例:
User.jsにname,emailなどのフィールドを設定。
✅ コード例(models/User.js)
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String,
});
module.exports = mongoose.model('User', UserSchema);
📌 リクエストの流れを図示するとこんな感じ!
[クライアント] → (GET /users/123) → [routes/userRoutes.js]
→ [controllers/userController.js]
→ [services/userService.js]
→ [repositories/userRepository.js]
→ [models/User.js] → [データベース] 🔄
🎯 まとめ
バックエンドのデータの流れを理解すると、
✅ 役割が明確になり、コードが整理される!
✅ 開発がスムーズになり、保守しやすくなる!
✅ 大規模プロジェクトにも対応しやすくなる!
初心者の方は、まず controllers/, models/, routes/ の流れを実装してみましょう!💡
🔰 「データの流れで他に知りたいことがあれば、ぜひコメントください!」 🚀