API Endpoint Reference
Relevant source files
The following files were used as context for generating this wiki page:
This document provides a comprehensive reference for the backend API of the E-Commerce platform. The API is built with Node.js and Express.js, serving as the backbone for all frontend operations, including user management, product catalog, order processing, and the unique sentiment analysis feature for product reviews.
The API is structured around RESTful principles, with routes organized by resource type (e.g., users, products, orders). It incorporates security middleware, input validation, and authentication to ensure data integrity and secure access. A key feature is the integration with a Hugging Face model to perform sentiment analysis on user-submitted reviews, providing valuable insights to sellers.
API Architecture and Middleware
The core of the API is configured in backend/app.js. It sets up an Express server and integrates several crucial middleware components to handle requests, security, and data parsing before they reach the route handlers.
The following diagram illustrates the lifecycle of an incoming API request as it passes through the configured middleware.
This diagram shows the sequence of middleware processing for each API request.
Sources: backend/app.js:14-41
Security and Data Handling Middleware
The application employs a suite of middleware to enhance security and properly handle incoming data.
| Middleware | Purpose |
|---|---|
cors | Enables Cross-Origin Resource Sharing, allowing the frontend application to communicate with the API. |
express-rate-limit | Limits the number of requests from a single IP to prevent brute-force attacks (100 requests per 15 minutes). |
helmet | Sets various HTTP headers to secure the application from common web vulnerabilities like XSS. |
express.json, bodyParser | Parses incoming request bodies with JSON payloads and URL-encoded data. |
cookie-parser | Parses Cookie header and populates req.cookies. |
express-mongo-sanitize | Sanitizes user-supplied data to prevent NoSQL query injection attacks. |
ErrorHandler | A custom error handling middleware to catch and format errors. |
Sources: backend/app.js:6-41, backend/app.js:132-133
API Routes
All API routes are prefixed with /api/v2/. The main application file, app.js, maps specific resource paths to their respective controller files.
| Route Prefix | Controller File | Description |
|---|---|---|
/api/v2/user | user.js | Handles user registration, login, profile updates, and authentication. |
/api/v2/product | product.js | Manages product creation, retrieval, updates, deletion, and reviews. |
/api/v2/order | order.js | Manages order creation and retrieval. |
/api/v2/shop | shop.js | Handles shop-related operations. |
/api/v2/event | event.js | Manages promotional events. |
/api/v2/coupon | coupounCode.js | Manages discount coupon codes. |
/api/v2/payment | payment.js | Processes payments via Stripe. |
/api/v2/conversation | conversation.js | Manages real-time chat conversations. |
/api/v2/message | message.js | Handles sending and receiving chat messages. |
/api/v2/withdraw | withdraw.js | Manages seller withdrawal requests. |
Sources: backend/app.js:77-87, README.md:193-215
Input Validation
The API uses express-validator to validate and sanitize incoming data for many endpoints. This is managed in backend/middleware/validator.js. Validation rules are defined for specific operations like user registration or product creation.
Example: User Registration Validation Rules
| Field | Validation Rules | Error Message |
|---|---|---|
name | Not empty, 2-50 chars, letters/spaces only | "Name is required", "Name must be between 2 and 50 characters", etc. |
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-40
Product Endpoints (/api/v2/product)
The product controller is responsible for all CRUD operations related to products, as well as handling product reviews and their sentiment analysis.
| Method | Endpoint | Authentication | Description |
|---|---|---|---|
POST | /create-product | Seller | Creates a new product. Handles multiple image uploads. |
PUT | /update-product | Seller | Updates an existing product. |
GET | /get-all-products-shop/:id | Public | Retrieves all products for a specific shop, with sentiment analysis results on reviews. |
DELETE | /delete-shop-product/:id | Seller | Deletes a product and its associated images from storage. |
GET | /get-all-products | Public | Retrieves all products from all shops. |
PUT | /create-new-review | User | Submits a new review or updates an existing one for a product. |
GET | /admin-all-products | Admin | Retrieves all products for administrative purposes. |
Sources: backend/controller/product.js
Product Creation and Image Handling
The POST /create-product endpoint uses multer middleware to handle multipart/form-data, specifically for image uploads.
- The request body contains product details (
name,description,price, etc.) and theshopId. upload.array('images')processes the uploaded files.- The controller logic verifies the
shopId. - Filenames of the uploaded images are stored as an array of strings in the
imagesfield of the product model. - A new
Productrecord is created in the database.
Sources: backend/controller/product.js:12-36
Review Submission and Updates
The PUT /create-new-review endpoint allows authenticated users to submit reviews.
- Request Body:
{ user, rating, comment, productId, orderId } - The system finds the product by
productId. - It checks if the user has already reviewed this product.
- If yes, it updates the existing review.
- If no, it adds a new review object to the product's
reviewsarray.
- It recalculates the product's average
ratingsand saves the updated product.
This flow is initiated from the frontend, for example, in the UserOrderDetails component after an order is delivered.
Sources: backend/controller/product.js:218-261, frontend/src/components/UserOrderDetails.jsx:30-47
Sentiment Analysis Integration
A core feature of the platform is the automated sentiment analysis of product reviews. This is handled by the analyzeSentiment.js controller and integrated into the GET /get-all-products-shop/:id endpoint.
Sentiment Analysis Flow
The following diagram shows the process of analyzing a review's sentiment.
This flowchart details how product reviews are enriched with sentiment data.
*Sources: backend/controller/product.js:100-128, backend/controller/analyzeSentiment.js *
Sentiment Analysis Service (analyzeSentiment.js)
This module communicates with an external Hugging Face Inference API to perform the analysis.
- Model Used:
finiteautomata/bertweet-base-sentiment-analysis checkModelStatus(): Before making analysis requests, the system can check if the model is loaded and ready on the Hugging Face servers. The product retrieval endpoint waits in a loop until the model is available.analyzeSentiment(review): Sends the review text as an input to the model's API endpoint and returns the resulting sentiment scores.getDominantLabel(result): Processes the API response, which is an array of labels with scores (e.g.,[{label: 'NEU', score: 0.8}, {label: 'POS', score: 0.1}]), and returns the label with the highest score.
Sources: backend/controller/analyzeSentiment.js:4-36
Sequence Diagram: Retrieving Products with Sentiment
This diagram shows the interactions between the client, the API, the database, and the external sentiment analysis service when a user views products from a specific shop.
This sequence diagram illustrates the data flow for fetching products and analyzing review sentiments.
Sources: backend/controller/product.js:96-133, backend/controller/analyzeSentiment.js