Description of the code - Hala-f-Habash/Support-Orphans GitHub Wiki

Description of the code

This is a description of the project and the codes contained in it

1. Data Base table

1.1 HopeConnect.sql

A database table that contains the created tables and the relationships between the tables.

2. Config Folder

2.1 db.js

Summary

This file configures and exports a MySQL connection pool using environment variables. It:

  • Loads database credentials from a .env file.
  • Validates that all required variables are set.
  • Creates a connection pool using mysql2/promise.
  • Exports the pool for use across the application to run database queries efficiently.

3. Middleware folder

3.1 authMiddleware.js

This file protects routes by verifying JWT tokens from the Authorization header. It checks if the token is present, valid, and not blacklisted. If valid, it attaches the user to the request and allows access.

const jwt = require('jsonwebtoken');
const { isBlacklisted } = require('../utils/tokenBlacklist');

exports.authenticate = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader?.split(' ')[1];

  if (!token) return res.sendStatus(401);
  if (isBlacklisted(token)) return res.status(403).json({ error: 'Token is revoked' });

  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
};

3.2 validateInput.js

This middleware uses express-validator to check request input. If validation errors exist, it returns a 422 response; otherwise, it proceeds to the next middleware.

//This middleware ensures that the input data is valid using express-validator.

const { validationResult } = require('express-validator');

exports.validate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }
  next();
};

3.3 uploadImage.js

This file configures multer for handling file uploads. It stores files in the uploads/ directory with unique filenames and only allows .jpg, .jpeg, and .png formats.

const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads/'),
  filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});

const fileFilter = (req, file, cb) => {
  const allowed = ['.jpg', '.jpeg', '.png'];
  const ext = path.extname(file.originalname).toLowerCase();
  cb(null, allowed.includes(ext));
};

const upload = multer({ storage, fileFilter });
module.exports = upload;

4. Validations folder

The validations/ folder checks all incoming data for security and correctness before processing. It uses express-validator to enforce rules per module, blocking malformed or dangerous input. This ensures data integrity, maintains consistent formatting across the app, it helps return descriptive validation errors via middleware.

4.1 addServiceRequestValidation.js

4.2 createCampaignValidation.js

4.3 createDonationCampValidation.js

4.4 deliveryValidation.js

4.5 donationValidation.js

4.6 driverValidation.js

4.7 loginValidation.js

4.8 orphanValidation.js

4.9 registerValidation.js

4.10 ReviewValidation.js

4.11 volunteerValidation.js

5. Services folder

The services/ folder contains the core business logic, acting as a middle layer between controllers and database operations. It centralizes business rules, transaction management, and reusable operations while ensuring security and consistency. This separation makes the application more maintainable, testable, and scalable.

5.1 authService.js

5.2 campaignService.js

5.3 deliveryService.js

5.4 donationService.js

5.5 driverService.js

5.6 financeService.js

5.7 logoutService.js

5.8 orphanageRequestService.js

5.9 orphanService.js

5.10 partnerService.js

5.11 paymentService.js

5.12 ReviewService.js

5.13 volunteerMatchService.js

5.14 volunteerService.js

6. Controller folder

The controllers/ folder handles HTTP-specific logic (requests/responses), acting as the bridge between API routes and business logic (services). It parses input (body/query params), validates roles/permissions, and formats proper responses—keeping HTTP concerns separate from core operations. This ensures clean error handling, better testability, and scalability.

6.1 authController.js

6.2 campaignController.js

6.3 deliveryController.js

6.4 donationController.js

6.5 driverController.js

6.6 financeController.js

6.7 logoutController.js

6.8 orphanageRequestController.js

6.9 orphanController.js

6.10 partnerController.js

6.11 ReviewsController.js

6.12 volunteerController.js

6.13 volunteerMatchController.js

7. app.js File

7.1 Core Configuration

The file initializes the Express application and loads environment variables, serving as the foundational setup for the HopeConnect backend. It establishes the basic server structure before adding routes and middleware.

const express = require('express');
const app = express();
require('dotenv').config();

7.2 Route Management

All API endpoints are organized into logical route groups, with separate route handlers for authentication, user management, orphan operations, donations, volunteers, campaigns, and other key features. This modular approach keeps the API structure clean and maintainable.

const orphans = require('./routes/orphanRoutes');
const donation = require("./routes/donationRoutes");
const volunteers = require('./routes/volunteerRoutes');

7.3 Middleware Implementation

The application uses essential middleware, including JSON request body parsing and static file serving for uploads. These middleware components handle fundamental request processing tasks before reaching route handlers.

app.use(express.json());
app.use('/uploads', express.static('uploads'));

7.4 API Endpoint Structure

Routes follow a consistent RESTful pattern with '/api' prefix, grouping related endpoints together. The authentication, user, orphan, donation, and volunteer routes form the core of the application's functionality.

app.use('/api/orphans', orphans);
app.use('/api/donations', donation);
app.use('/api/volunteers', volunteers);

7.5 Server Initialization

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

8. .env file

The .env file contains all sensitive configuration variables for the HopeConnect application, keeping them separate from the main codebase for security. It specifies the server port (3000), MySQL database credentials (host, username, password, and database name), JWT secret key for authentication security, and SMTP email settings using Gmail for sending emails. The email configuration includes the SMTP server details, port, account email, and an app-specific password for secure access. This centralized configuration allows easy environment-specific adjustments without modifying application code.