Overview
The Node.js Express service is a RESTful API microservice that provides user management, product catalog, authentication, and reporting functionality. It uses Express.js with Sequelize ORM and PostgreSQL for production environments.Technology Stack
- Framework: Express.js 4.18+
- ORM: Sequelize 6.35
- Database: PostgreSQL (SQLite for testing)
- Authentication: JWT (jsonwebtoken)
- Password Hashing: bcryptjs
- Validation: express-validator
- CORS: cors middleware
- Testing: Jest with Supertest
Setup and Installation
Project Structure
Configuration
The service configuration is centralized insrc/config.js:3:
src/config.js
Database Models
All models are defined using Sequelize insrc/models/index.js.
User Model
Defined insrc/models/index.js:23:
src/models/index.js
Product Model
Defined insrc/models/index.js:55:
src/models/index.js
Order Model
Defined insrc/models/index.js:82:
src/models/index.js
Middleware
Authentication Middleware
JWT authentication middleware insrc/middleware/auth.js:4:
src/middleware/auth.js
Validation Middleware
Request validation using express-validator insrc/middleware/validate.js:5:
src/middleware/validate.js
API Routes
Authentication Routes
Defined insrc/routes/auth.js and mounted at /api/auth:
POST /api/auth/register
Register a new user insrc/routes/auth.js:11:
src/routes/auth.js
POST /api/auth/login
Authenticate user and return JWT token insrc/routes/auth.js:49:
src/routes/auth.js
User Routes
Defined insrc/routes/users.js and mounted at /api/users:
GET /api/users/:id
Get user by ID (requires authentication) insrc/routes/users.js:9.
GET /api/users/me/profile
Get current user’s profile insrc/routes/users.js:15:
src/routes/users.js
PUT /api/users/me/profile
Update current user’s profile insrc/routes/users.js:27:
src/routes/users.js
Product Routes
Defined insrc/routes/products.js and mounted at /api/products:
GET /api/products
List products with pagination insrc/routes/products.js:9:
src/routes/products.js
GET /api/products/search
Search products using Fuse.js fuzzy search insrc/routes/products.js:34:
src/routes/products.js
GET /api/products/:id
Get a single product by ID insrc/routes/products.js:61.
POST /api/products
Create a new product (requires authentication) insrc/routes/products.js:75:
src/routes/products.js
Report Routes
Defined insrc/routes/reports.js and mounted at /api/reports:
GET /api/reports/sales
Generate HTML sales report (requires authentication) insrc/routes/reports.js:12:
src/routes/reports.js
Application Entry Point
The main application is configured insrc/index.js:9:
src/index.js
Testing
The service uses Jest with Supertest for API testing.Running Tests
Test Setup
Test configuration uses SQLite in-memory database intests/auth.test.js:5:
tests/auth.test.js
Example Tests
Fromtests/auth.test.js:17:
tests/auth.test.js
Dependencies
Frompackage.json:
package.json
Available Scripts
Frompackage.json:6: