This is the backend API for the THDC Complaint Management System, built with Node.js, Express, TypeScript, and MongoDB.
- Architecture Overview
- Directory Structure
- Setup and Installation
- API Endpoints
- Authentication and Authorization
- Database Models
- Middleware
- Controllers
- Utilities
- Deployment
- Error Handling
The backend follows the MVC (Model-View-Controller) architecture pattern:
- Models: Define the database schema and business logic for data entities
- Controllers: Handle incoming requests, process data, and send responses
- Routes: Define API endpoints and connect them to controllers
- Middleware: Provide cross-cutting functionality like authentication and error handling
- Utils: Contain helper functions and utilities used across the application
backend/
├── app.ts # Express application setup
├── server.ts # Server entry point
├── config.env # Environment variables
├── tsconfig.json # TypeScript configuration
├── package.json # Dependencies and scripts
├── render.yaml # Render.com deployment configuration
├── render-build.sh # Build script for Render.com
├── deploy.js # JavaScript fallback for deployment
├── build.js # Build script
├── controllers/ # Request handlers
│ ├── ComplaintController.ts
│ └── UserController.ts
├── models/ # Database schemas
│ ├── complaintModel.ts
│ └── userModel.ts
├── routes/ # API routes
│ ├── complaintRoute.ts
│ └── userRoute.ts
├── middleware/ # Middleware functions
│ ├── auth.ts
│ ├── catchAsyncError.ts
│ └── error.ts
└── utils/ # Utility functions
├── errorhandler.ts
└── jwtToken.ts
- Node.js (v18 or higher)
- MongoDB (local or Atlas connection)
-
Install dependencies:
npm install
-
Create a
config.envfile with the following variables:PORT=6050 MONGODB_URL=your_mongodb_connection_string JWT_SECRET=your_jwt_secret ADMIN_REGISTRATION_CODE=your_admin_code -
Run development server:
npm run dev
-
Build for production:
npm run build
-
Start production server:
npm start
-
POST /api/v1/register: Register a new user- Body:
{ name, email, password, role } - Role can be "user", "employee", or "admin" (admin requires registration code)
- Body:
-
POST /api/v1/login: User login- Body:
{ email, password } - Returns JWT token in cookie
- Body:
-
GET /api/v1/logout: User logout- Clears authentication cookie
GET /api/v1/me: Get current user profilePUT /api/v1/update-profile: Update user profilePUT /api/v1/update-password: Update user passwordGET /api/v1/get-all-workers: Get all workers (employee/admin only)
-
POST /api/v1/register-complaint: Register a new complaint- Body:
{ title, description, priority, location }
- Body:
-
GET /api/v1/get-all-my-complaints: Get all complaints by current user -
GET /api/v1/get-all-employee-complaints: Get all complaints (employee/admin only) -
GET /api/v1/find-arrived-complaints: Get newly arrived complaints (employee/admin only) -
PUT /api/v1/assign-complaint-to-worker/:id: Assign complaint to worker- Body:
{ workerId, workerName }
- Body:
-
PUT /api/v1/change-status-of-complaint/:id: Update complaint status- Body:
{ status }
- Body:
-
GET /api/v1/filter-complaints: Filter complaints by various parameters- Query params:
status,priority,worker, etc.
- Query params:
Authentication is implemented using JSON Web Tokens (JWT). The system has three user roles:
- User: Regular users who can register complaints and view their own complaints
- Employee: Can manage complaints, assign them to workers, and update their status
- Admin: Has full access to all features and can manage users
The authentication flow works as follows:
- User logs in with email and password
- Server validates credentials and generates a JWT token
- Token is sent to the client in an HTTP-only cookie
- For subsequent requests, the token is extracted from the cookie or Authorization header
- Middleware verifies the token and attaches the user to the request object
The User model defines the schema for users in the system:
interface IUser extends Document {
name: string;
email: string;
password: string;
role: string;
createdAt: Date;
comparePassword(enteredPassword: string): Promise<boolean>;
getJWTToken(): string;
}Key features:
- Password hashing using bcrypt
- Method to compare passwords for authentication
- Method to generate JWT tokens
- Pre-save hook to hash passwords
The Complaint model defines the schema for complaints in the system:
interface IComplaint extends Document {
title: string;
description: string;
status: string;
priority: string;
location: string;
user: IUser | Schema.Types.ObjectId;
worker: {
id?: Schema.Types.ObjectId;
name?: string;
};
createdAt: Date;
updatedAt: Date;
}Key features:
- Reference to user who created the complaint
- Worker assignment information
- Status tracking (pending, in-progress, resolved)
- Priority levels (low, medium, high)
This middleware handles authentication and role-based authorization:
isAuthenticated: Verifies JWT token and attaches user to requestauthorizeRoles: Restricts access based on user roles
Centralized error handling middleware that:
- Formats error responses
- Handles different types of errors (validation, authentication, etc.)
- Provides appropriate HTTP status codes
A utility middleware that wraps controller functions to handle async errors without try-catch blocks.
Handles user-related operations:
- User registration and login
- Profile management
- Password updates
- User listing (for admins)
Handles complaint-related operations:
- Creating new complaints
- Listing complaints (with filtering)
- Assigning complaints to workers
- Updating complaint status
- Filtering and searching complaints
Handles JWT token generation and cookie settings:
- Generates tokens with user ID payload
- Sets secure HTTP-only cookies
- Configures token expiration
Custom error class for consistent error handling across the application.
The backend is configured for deployment on Render.com using:
-
render.yaml: Defines the service configuration -
render-build.sh: Build script that:- Installs dependencies
- Attempts TypeScript compilation
- Falls back to JavaScript if compilation fails
- Sets up environment variables
-
deploy.js: JavaScript fallback version of the server for when TypeScript compilation fails
NODE_ENV:productionPORT:10000MONGODB_URL: MongoDB connection stringJWT_SECRET: Secret for JWT token generationADMIN_REGISTRATION_CODE: Code required for admin registration
The application implements a comprehensive error handling strategy:
- Custom Error Class:
utils/errorhandler.tsprovides a consistent error format - Async Error Wrapper:
middleware/catchAsyncError.tscatches errors in async functions - Global Error Handler:
middleware/error.tsprocesses all errors centrally - Validation Errors: Mongoose validation errors are properly formatted
- HTTP Status Codes: Appropriate status codes are used for different error types
Sets up the Express application:
- Configures middleware (CORS, body parser, cookie parser)
- Mounts API routes
- Sets up global error handler
The entry point of the application:
- Loads environment variables
- Connects to MongoDB
- Starts the HTTP server
- Sets up global error handlers for uncaught exceptions
A Node.js script that:
- Cleans the dist directory
- Installs TypeScript type definitions
- Attempts to compile TypeScript code
- Falls back to JavaScript if compilation fails
A simplified JavaScript version of the server that:
- Sets up basic Express routes
- Connects to MongoDB
- Provides minimal functionality for deployment
- Used as a fallback when TypeScript compilation fails
A bash script for Render.com deployment that:
- Installs dependencies
- Installs TypeScript globally
- Installs type definitions
- Attempts TypeScript compilation
- Falls back to JavaScript if compilation fails
Defines the Render.com service configuration:
- Service type and name
- Environment (Node.js)
- Repository and branch
- Build and start commands
- Environment variables