Backend API Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The backend for the E-Commerce platform is a Node.js application built with the Express.js framework. It provides a comprehensive RESTful API to support all functionalities of the web application, including user management, product and order processing, payments, and real-time chat. A key feature is the integration of an AI model for sentiment analysis of product reviews.
The architecture is modular, separating concerns into controllers, models, middleware, and utility functions. It employs a dual-database strategy using MongoDB (with Mongoose) for core e-commerce data and potentially MySQL (with Sequelize) for other features. Security is a primary focus, with JWT for authentication, input validation, and various security-focused middleware.
Sources: README.md, backend/app.js, backend/package.json
Core Technologies
The backend relies on a modern stack of Node.js libraries to provide its functionality.
| Technology | Purpose |
|---|---|
express | Web server framework for building the API. |
mongoose | ODM for interacting with the MongoDB database. |
sequelize | ORM for interacting with the MySQL database. |
jsonwebtoken | Implements JSON Web Token for user authentication. |
bcryptjs | Hashes user passwords for secure storage. |
multer & cloudinary | Handles file uploads, specifically for product images, storing them on Cloudinary. |
stripe | Integrates with the Stripe API for payment processing. |
axios | HTTP client used to make requests to external APIs (e.g., Hugging Face). |
helmet | Secures the app by setting various HTTP headers. |
express-rate-limit | Limits repeated requests to public APIs to prevent abuse. |
express-mongo-sanitize | Sanitizes user-supplied data to prevent NoSQL query injection. |
express-validator | Provides middleware for server-side data validation. |
openai / @google-cloud/translate | Integrated for AI and NLP tasks, specifically sentiment analysis. |
Sources: backend/package.json, backend/app.js:1-13
Application Structure
The backend code is organized into distinct directories, promoting a clean and maintainable codebase.
This diagram shows the main directories within the backend and their purpose.
Sources: README.md
Server Initialization and Middleware
The main application entry point is backend/app.js, which configures the Express server and its middleware pipeline.
Middleware Pipeline
The application uses several middleware functions to process incoming requests. They are executed sequentially for each request.
| Middleware | Description | File Reference |
|---|---|---|
cors | Enables Cross-Origin Resource Sharing, allowing the frontend to communicate with the API. | app.js:15-20 |
express-rate-limit | Applies rate limiting to all API routes to prevent brute-force attacks and abuse. | app.js:23-29 |
express.json / bodyParser | Parses incoming request bodies (JSON, URL-encoded). | app.js:32-34 |
cookie-parser | Parses Cookie header and populates req.cookies. | app.js:33 |
helmet | Sets various security-related HTTP headers to protect against common vulnerabilities. | app.js:37 |
mongo-sanitize | Removes characters like $ and . from request bodies to prevent NoSQL injection. | app.js:40 |
express.static | Serves static files from the ./uploads directory. | app.js:43 |
ErrorHandler | A custom final middleware to catch and handle all application errors. | app.js:125 |
The following diagram illustrates the flow of a request through the middleware chain.
Sources: backend/app.js:1-43, 125
Routing and Controllers
The API routes are defined in backend/app.js and are delegated to specific controller files found in the backend/controller/ directory. This modular approach keeps the main application file clean and organizes endpoints by resource.
Route Definitions
The primary API routes are prefixed with /api/v2/.
| Base Path | Controller File | Manages |
|---|---|---|
/api/v2/user | user.js | User registration, login, profile, etc. |
/api/v2/shop | shop.js | Shop creation, information, and management. |
/api/v2/product | product.js | Product creation, retrieval, and reviews. |
/api/v2/order | order.js | Order creation and management. |
/api/v2/payment | payment.js | Payment processing with Stripe. |
/api/v2/event | event.js | Promotional events. |
/api/v2/coupon | coupounCode.js | Discount coupon codes. |
/api/v2/conversation | conversation.js | Real-time chat conversations. |
/api/v2/message | message.js | Real-time chat messages. |
/api/v2/withdraw | withdraw.js | Seller withdrawal requests. |
Sources: backend/app.js:68-78, README.md
Authentication and Authorization
The API uses JSON Web Tokens (JWT) for securing endpoints. The isAuthenticated middleware is used to protect routes that require a logged-in user, while isAdmin restricts access to administrators only.
The flow for accessing a protected route is as follows:
- A user logs in via
POST /api/v2/user/login. - The server validates credentials and, if successful, returns a JWT stored in a cookie.
- For subsequent requests to protected routes, the browser sends the cookie containing the JWT.
- The
isAuthenticatedmiddleware verifies the token. If valid, it attaches the user's information to thereqobject and passes control to the next handler. If invalid, it returns an error.
An example of a protected route requiring admin privileges:
// backend/app.js:80-123
app.put(
"/api/v2/user/update-role/:id",
require("./middleware/auth").isAuthenticated,
require("./middleware/auth").isAdmin("Admin"),
// ... controller logic
);
Sources: backend/app.js:80-84, README.md
Authentication Sequence Diagram
This diagram shows the sequence for a user logging in and accessing a protected resource.
Sources: README.md, backend/app.js:68
Input Validation
Server-side validation is implemented using express-validator to ensure data integrity and security. The validation logic is defined in backend/middleware/validator.js.
Validation Rules Example
The validateUserRegistration middleware checks the user registration payload against a set of rules before it reaches the controller.
| Field | Validation Rule | Error Message |
|---|---|---|
name | Not empty, 2-50 chars, letters/spaces only | Name is required, Name must be... |
email | Not empty, valid email format | Email is required, Please provide a valid email |
password | Not empty, min 8 chars, 1 uppercase, 1 lowercase, 1 number, 1 special char | Password is required, Password must be at least 8 characters, etc. |
Sources: backend/middleware/validator.js:18-38
This validation is applied in the controller routes to reject invalid requests early.
Sources: backend/middleware/validator.js:5-15
Sentiment Analysis Integration
A standout feature of this backend is its ability to analyze the sentiment of product reviews using an external AI model. This process is handled by analyzeSentiment.js and integrated into the product controller.
Workflow
- Model Check: Before fetching reviews, the system checks if the Hugging Face model (
finiteautomata/bertweet-base-sentiment-analysis) is loaded and ready. - API Call: For each review comment, the
analyzeSentimentfunction sends a POST request to the Hugging Face Inference API. - Process Result: The API returns a sentiment score (e.g.,
POS,NEG,NEU). ThegetDominantLabelfunction selects the label with the highest score. - Inject Sentiment: The resulting sentiment is added to the review object before being sent to the client.
This flow is triggered when a client requests product data that includes reviews, such as on a product details page.
Conclusion
The backend architecture of the E-Commerce-Website-With-Sentiment-Analysis-For-Reviews project is robust, secure, and scalable. It follows best practices for Node.js development by using a modular structure, a comprehensive middleware pipeline for security and request processing, and a clear separation of concerns. The integration of external services for file storage (Cloudinary), payments (Stripe), and advanced AI-powered sentiment analysis (Hugging Face) demonstrates a modern, microservice-friendly approach to building a feature-rich e-commerce platform.
Sources: README.md, backend/app.js