Repository navigation
Test Management Endpoints
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
This document provides comprehensive API documentation for test management endpoints in the system. It covers the four primary endpoints for managing tests:
- POST /api/tests: Create a new test with teacher-only access control
- GET /api/tests: List tests with query parameters (teacherId, status) supporting both teacher-owned tests and student-class filtering
- GET /api/tests/:id: Retrieve a specific test with proper access validation
- PATCH /api/tests/:id: Update a test with ownership verification
The documentation includes request/response schemas validated by Zod schemas, role-based access control implementation, permission checking logic, error handling patterns, and practical examples for teacher test creation workflows, student test access patterns, and administrative test management scenarios.
The test management functionality spans both server-side and client-side components:
graph TB
subgraph "Client-Side"
CT["CreateTest Page<br/>client/src/pages/create-test.tsx"]
TDF["TestDetailsForm<br/>client/src/components/test/test-details-form.tsx"]
QC["QueryClient<br/>client/src/lib/queryClient.ts"]
end
subgraph "Server-Side"
SRV["Server Entry<br/>server/index.ts"]
ROUTES["Routes Handler<br/>server/routes.ts"]
SCHEMA["Zod Schemas<br/>shared/schema.ts"]
MONGO["MongoDB Schemas<br/>shared/mongo-schema.ts"]
STORAGE["Storage Layer<br/>server/storage.ts"]
end
CT --> TDF
TDF --> QC
QC --> ROUTES
ROUTES --> STORAGE
ROUTES --> SCHEMA
STORAGE --> MONGO
SRV --> ROUTES
Diagram sources
- server/index.ts
- server/routes.ts
- shared/schema.ts
- shared/mongo-schema.ts
- server/storage.ts
Section sources
- server/index.ts
- server/routes.ts
The test management system consists of several key components working together:
The system uses Zod schemas for strict input validation:
-
insertTestSchema: Defines the structure and validation rules for test creation/update -
insertUserSchema: Provides user-related validation for session management - Database schema mapping: MongoDB document structure for persistent storage
The storage layer provides database abstraction with methods for:
- Test CRUD operations (create, read, update)
- Test listing with filtering by teacherId and status
- Student-class based filtering for test discovery
- Ownership verification for access control
Each endpoint implements comprehensive validation and access control:
- Authentication checks using session data
- Role-based authorization (teacher vs student)
- Ownership verification for test operations
- Proper error handling with appropriate HTTP status codes
Section sources
- shared/schema.ts
- shared/mongo-schema.ts
- server/storage.ts
The test management architecture follows a layered approach with clear separation of concerns:
sequenceDiagram
participant Client as "Client Application"
participant Routes as "Route Handlers"
participant Storage as "Storage Layer"
participant DB as "MongoDB"
participant Session as "Session Store"
Client->>Routes : HTTP Request (POST /api/tests)
Routes->>Session : Verify authentication
Routes->>Routes : Validate role (teacher)
Routes->>Routes : Parse and validate input (Zod)
Routes->>Storage : Create test
Storage->>DB : Insert test document
DB-->>Storage : Test created
Storage-->>Routes : Test data
Routes-->>Client : HTTP Response (201)
Note over Client,DB : Access control enforced throughout
Diagram sources
- server/routes.ts
- server/storage.ts
The architecture ensures:
- Security: All operations require authenticated sessions with role validation
- Data Integrity: Strict input validation using Zod schemas
- Access Control: Fine-grained permissions based on user roles and ownership
- Scalability: Clear separation between presentation, business logic, and data access layers
This endpoint enables teachers to create new tests with comprehensive validation and access control.
The request body must conform to the insertTestSchema with the following structure:
- title: string (required, min length 1)
- description: string (optional)
- subject: string (required, min length 1)
- class: string (required, min length 1)
- teacherId: number (required, must match authenticated user)
- totalMarks: number (default: 100)
- duration: number (default: 60)
- testDate: string or date (required)
- questionTypes: array of strings (required, min length 1)
- status: enum ["draft", "published", "completed"] (default: "draft")
Successful creation returns a complete test object with additional fields:
- id: number (auto-generated)
- createdAt: date (auto-generated)
- All fields from the request schema
-
Authentication: Requires active session (
req.session.userId) - Role Verification: Must be "teacher" role
-
Ownership Validation:
teacherIdmust match the authenticated user's ID - Input Validation: Uses Zod schema for comprehensive validation
- 401 Unauthorized: Missing or invalid session
- 400 Bad Request: Invalid input data (Zod validation errors)
- 403 Forbidden: Non-teacher users or ownership mismatch
- 500 Internal Server Error: Database or system errors
Section sources
- server/routes.ts
- shared/schema.ts
This endpoint provides flexible test listing with support for both teacher-owned tests and student-class filtering.
- teacherId: number (optional) - Filter by specific teacher
- status: string (optional) - Filter by test status
- Authentication: Requires active session
-
Role-Based Filtering:
- Teachers: Can access their own tests or all tests if admin (admin role not explicitly defined in code)
- Students: Can only access tests for their class
- Class-Based Filtering: Students receive tests filtered by their class enrollment
Returns an array of test objects matching the query criteria, each with:
- Complete test data including id, createdAt, and all request fields
-
Teacher Workflow:
GET /api/tests?teacherId=123&status=published -
Student Workflow:
GET /api/tests?status=completed(automatically filtered by student's class)
Section sources
- server/routes.ts
- server/storage.ts
This endpoint retrieves a specific test with comprehensive access validation.
- id: number (required) - Test identifier
- Authentication: Requires active session
- Existence Check: Validates test existence
-
Permission Validation:
-
Teachers: Can access tests where
teacherIdmatches their ID -
Students: Can access tests where
classmatches their class enrollment
-
Teachers: Can access tests where
- Input Validation: Converts path parameter to integer with error handling
Returns the complete test object if accessible, otherwise returns appropriate error
- 400 Bad Request: Invalid test ID format
- 401 Unauthorized: Missing session
- 403 Forbidden: Insufficient permissions or class mismatch
- 404 Not Found: Test does not exist
Section sources
- server/routes.ts
This endpoint allows authorized updates to existing tests with ownership verification.
- id: number (required) - Test identifier to update
Partial test data using insertTestSchema.partial() allowing selective field updates:
- title, description, subject, class, totalMarks, duration, testDate, questionTypes, status
- Authentication: Requires teacher role
- Existence Check: Validates test existence
- Ownership Verification: Ensures teacher owns the test
- Partial Validation: Uses Zod partial schema for flexible updates
Returns the updated test object with all fields
- 400 Bad Request: Invalid test ID or validation errors
- 401 Unauthorized: Non-teacher users
- 403 Forbidden: Test ownership verification failed
- 404 Not Found: Test does not exist
Section sources
- server/routes.ts
graph TD
subgraph "External Dependencies"
ZOD["Zod Validation"]
MONGOOSE["Mongoose ORM"]
EXPRESS["Express.js"]
SESSION["Express Session"]
end
subgraph "Core Modules"
ROUTES["Routes Module"]
STORAGE["Storage Module"]
SCHEMA["Validation Schemas"]
MODELS["MongoDB Models"]
end
subgraph "Client Integration"
QUERY["Query Client"]
FORM["Test Form"]
PAGE["Create Test Page"]
end
ROUTES --> SCHEMA
ROUTES --> STORAGE
STORAGE --> MODELS
STORAGE --> MONGOOSE
ROUTES --> EXPRESS
ROUTES --> SESSION
QUERY --> ROUTES
FORM --> QUERY
PAGE --> FORM
SCHEMA --> ZOD
MODELS --> MONGOOSE
Diagram sources
- server/routes.ts
- server/storage.ts
- shared/schema.ts
- shared/mongo-schema.ts
- Zod Validation: Provides compile-time type safety and runtime validation
- Mongoose: Handles MongoDB operations and document modeling
- Express Session: Manages user authentication state across requests
- React Query: Client-side caching and state management for API calls
- Low Coupling: Routes depend only on storage interface, not implementation details
- High Cohesion: Each module has a single responsibility (routing, validation, storage)
- Clear Contracts: Interfaces define explicit boundaries between components
Section sources
- server/storage.ts
The test management system incorporates several performance optimizations:
- Test queries support filtering by teacherId and status efficiently
- Test assignment queries utilize composite indexes for optimal performance
- Auto-increment counters prevent ID conflicts and improve insertion performance
- React Query provides automatic client-side caching for test lists
- Session-based authentication reduces repeated database lookups
- Query invalidation ensures data consistency across updates
- Modular architecture allows for horizontal scaling
- Database abstraction enables potential migration to other storage systems
- Stateless route handlers support load balancing
- 401 Unauthorized: Verify user session is active and contains role information
- Session Not Persisting: Check session store configuration and cookie settings
- Role Mismatch: Ensure user role is properly set during registration/login
- 400 Bad Request: Review Zod validation error messages for specific field issues
- Missing Fields: Ensure all required fields are present in request body
- Type Mismatches: Verify data types match schema expectations
- 403 Forbidden: Confirm user has proper role and ownership permissions
- Class Filtering Issues: Verify student class enrollment matches test class
- Teacher vs Student Confusion: Check that teacherId matches authenticated user
- Connection Failures: Verify MongoDB connection string and network connectivity
- Query Performance: Monitor slow query logs and consider adding appropriate indexes
- Data Consistency: Use transactions for operations requiring atomicity
Section sources
- server/routes.ts
- server/storage.ts
The test management endpoints provide a robust, secure, and scalable solution for educational assessment management. The implementation demonstrates strong adherence to security best practices through comprehensive role-based access control, strict input validation, and proper error handling.
Key strengths of the implementation include:
- Security: Multi-layered access control with session-based authentication
- Data Integrity: Comprehensive validation using Zod schemas
- Flexibility: Support for both teacher-owned tests and student-class filtering
- Maintainability: Clean separation of concerns with modular architecture
- Developer Experience: Clear error messages and comprehensive documentation
The system successfully balances security requirements with usability, providing appropriate access patterns for different user roles while maintaining data consistency and performance. The modular design facilitates future enhancements such as administrative test management capabilities and expanded filtering options.