mcp-quiz-server
Version:
🧠AI-Powered Quiz Management via Model Context Protocol (MCP) - Create, manage, and take quizzes directly from VS Code, Claude, and other AI agents.
291 lines (290 loc) • 11.5 kB
JavaScript
"use strict";
/**
* @fileoverview Quiz Routes - Clean Architecture HTTP routes for quiz operations
* @version 1.0.0
* @since 2025-07-31
* @lastUpdated 2025-07-31
* @module QuizRoutes
* @description HTTP routes for quiz management following clean architecture principles.
* Separates route definitions from controller logic and provides
* proper error handling and middleware integration.
* @contributors Claude Code Agent
* @dependencies express, ControllerFactory, error-handler, audit-logger
* @requirements REQ_API_001, REQ_ARCH_002, REQ_PERF_001
* @testCoverage Route-level integration tests
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.createQuizRoutes = createQuizRoutes;
const express = __importStar(require("express"));
const error_handler_1 = require("../../../shared/error-handler");
/**
* Creates quiz-related HTTP routes following clean architecture patterns.
*
* @description Sets up all quiz-related endpoints with proper validation,
* error handling, and audit logging. Uses dependency injection
* for controllers and services.
*
* @param config - Configuration object with dependencies
* @returns Express router with quiz routes
*
* @example
* ```typescript
* const quizRouter = createQuizRoutes({
* controllerFactory,
* auditLogger,
* legacyService: quizService
* });
* app.use('/quiz', quizRouter);
* ```
*
* @since 2025-07-31
* @author Claude Code Agent
* @requirements REQ_API_001 (Quiz CRUD Operations)
* @accessibility Standard HTTP REST API
*/
function createQuizRoutes(config) {
const router = express.Router();
const { controllerFactory, auditLogger, authMiddleware } = config;
/**
* @swagger
* /quiz/all:
* get:
* tags:
* - Quizzes
* summary: List all quizzes
* description: Retrieve all available quizzes with clean architecture controller and legacy fallback
* responses:
* 200:
* description: List of quizzes
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/Quiz'
* 500:
* description: Server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
router.get('/all', (0, error_handler_1.asyncHandler)(async (req, res, next) => {
if (!controllerFactory || !controllerFactory.hasCleanArchitecture()) {
return res.status(503).json({
error: 'Clean Architecture service not available',
message: 'Legacy services have been removed. Clean Architecture required.'
});
}
const quizController = controllerFactory.createQuizController();
await quizController.listQuizzes(req, res, next);
}));
/**
* @swagger
* /quiz/{id}:
* get:
* tags:
* - Quizzes
* summary: Get quiz by ID
* description: Retrieve a specific quiz by its unique identifier
* parameters:
* - in: path
* name: id
* required: true
* description: Unique quiz identifier
* schema:
* type: string
* responses:
* 200:
* description: Quiz details
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Quiz'
* 404:
* description: Quiz not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
router.get('/:id', (0, error_handler_1.asyncHandler)(async (req, res, next) => {
if (!controllerFactory || !controllerFactory.hasCleanArchitecture()) {
return res.status(503).json({
error: 'Clean Architecture service not available',
message: 'Legacy services have been removed. Clean Architecture required.'
});
}
const quizController = controllerFactory.createQuizController();
await quizController.getQuiz(req, res, next);
}));
/**
* @swagger
* /quiz/create:
* post:
* tags:
* - Quizzes
* summary: Create new quiz
* description: Create a new quiz with validation, clean architecture controller, and audit logging
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Quiz'
* responses:
* 201:
* description: Quiz created successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Quiz'
* 400:
* description: Invalid quiz data
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 401:
* description: Unauthorized - authentication required
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 403:
* description: Forbidden - insufficient permissions
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
router.post('/create', (authMiddleware === null || authMiddleware === void 0 ? void 0 : authMiddleware.requirePermission)
? authMiddleware.requirePermission('quiz:create')
: (req, res, next) => {
error_handler_1.Logger.warn('🚨 SECURITY WARNING: /quiz/create endpoint is UNPROTECTED');
next();
}, (0, error_handler_1.asyncHandler)(async (req, res, next) => {
var _a;
// Validate quiz format using centralized validator
(0, error_handler_1.validateQuizFormat)(req.body);
if (!controllerFactory || !controllerFactory.hasCleanArchitecture()) {
return res.status(503).json({
error: 'Clean Architecture service not available',
message: 'Legacy services have been removed. Clean Architecture required.'
});
}
const quizController = controllerFactory.createQuizController();
await quizController.createQuiz(req, res, next);
// Audit log quiz creation (if response was successful)
if (res.statusCode === 201) {
const responseBody = res.locals.quizData || { id: 'unknown', title: req.body.title };
auditLogger.logUserAction('QUIZ_CREATE', {
resource: 'quiz',
resourceId: responseBody.id,
ipAddress: req.ip || req.connection.remoteAddress,
userAgent: req.get('User-Agent'),
success: true,
metadata: {
quizTitle: req.body.title,
questionCount: ((_a = req.body.questions) === null || _a === void 0 ? void 0 : _a.length) || 0,
category: req.body.category,
enhancedController: true,
},
});
error_handler_1.Logger.info('Quiz created via Clean Architecture controller', {
quizId: responseBody.id,
title: req.body.title,
});
}
}));
/**
* POST /quiz/submit - Submit quiz answers
* Enhanced with validation, Clean Architecture controller, and audit logging
*/
router.post('/submit', (0, error_handler_1.asyncHandler)(async (req, res, next) => {
const { quizId, answers } = req.body;
if (!quizId || !answers) {
throw (0, error_handler_1.createValidationError)('Quiz ID and answers are required');
}
if (typeof answers !== 'object' || Array.isArray(answers)) {
throw (0, error_handler_1.createValidationError)('Answers must be an object with question IDs as keys');
}
if (!controllerFactory || !controllerFactory.hasCleanArchitecture()) {
return res.status(503).json({
error: 'Clean Architecture service not available',
message: 'Legacy services have been removed. Clean Architecture required.'
});
}
const quizController = controllerFactory.createQuizController();
await quizController.submitQuiz(req, res, next);
// Audit log quiz submission (if response was successful)
if (res.statusCode === 200) {
const responseBody = res.locals.quizData || { quizId, score: 'unknown' };
auditLogger.logUserAction('QUIZ_SUBMIT', {
resource: 'quiz',
resourceId: quizId,
ipAddress: req.ip || req.connection.remoteAddress,
userAgent: req.get('User-Agent'),
success: true,
metadata: {
score: responseBody.score,
totalQuestions: responseBody.totalQuestions,
answerCount: Object.keys(answers).length,
enhancedController: true,
},
});
error_handler_1.Logger.info('Quiz submitted via Clean Architecture controller', {
quizId,
score: responseBody.score,
});
}
}));
return router;
}