Application Architecture Overview - pacificnm/wiki-ai GitHub Wiki

🧩 Application Architecture Overview

This document explains how the models, services, and controllers work together in the application.


📦 Layers Overview

Layer Responsibility
Model Defines MongoDB schema via Mongoose
Service Contains reusable business logic and direct interaction with the database
Controller Handles HTTP requests and responses; calls services to perform actions

🔗 Flow Diagram

Client / Frontend
        ↓
  [ Routes (Express) ]
        ↓
  [ Controllers ]
        ↓
  [ Services ]
        ↓
  [ Mongoose Models ]

🧾 Example: Document

1️⃣ Model

// models/Document.js
import mongoose from 'mongoose';

const documentSchema = new mongoose.Schema({
  title: String,
  body: String,
  authorId: mongoose.Schema.Types.ObjectId,
  tags: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Tag' }],
  categories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Category' }],
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now },
});

export default mongoose.model('Document', documentSchema);

2️⃣ Service

// services/documentService.js
import Document from '../models/Document.js';

export async function createDocument(data) {
  return await Document.create(data);
}

export async function getDocumentById(id) {
  return await Document.findById(id).populate('tags categories');
}

3️⃣ Controller

// controllers/documentController.js
import * as documentService from '../services/documentService.js';

export async function getDocument(req, res) {
  const doc = await documentService.getDocumentById(req.params.id);
  if (!doc) return res.status(404).json({ error: 'Not found' });
  res.json(doc);
}

export async function createDocument(req, res) {
  const doc = await documentService.createDocument(req.body);
  res.status(201).json(doc);
}

4️⃣ Route

// routes/documentRoutes.js
import express from 'express';
import * as documentController from '../controllers/documentController.js';

const router = express.Router();

router.get('/:id', documentController.getDocument);
router.post('/', documentController.createDocument);

export default router;

🛠 Example Usage in server/index.js

import express from 'express';
import documentRoutes from './routes/documentRoutes.js';

const app = express();

app.use(express.json());
app.use('/api/documents', documentRoutes);

app.listen(5000, () => {
  console.log('Server running on port 5000');
});

✅ Summary

  • Models define the data shape and connect to MongoDB.
  • Services abstract the business logic and interact with models.
  • Controllers orchestrate the flow, using services to respond to requests.
  • Routes connect HTTP endpoints to the appropriate controller methods.

This separation makes the system clean, testable, and scalable.