A production-ready, scalable RESTful API for merchant and e-commerce management
Getting Started β’ API Documentation β’ Features β’ Architecture β’ Contributing
- Features
- Tech Stack
- Getting Started
- Docker Deployment
- API Documentation
- Architecture
- Configuration
- Testing
- Contributing
- License
- ** Product Management** - Full CRUD operations with advanced filtering, sorting, and pagination
- Order Management - Complete order lifecycle with status tracking
- Authentication - JWT-based secure authentication
- Authorization - Role-Based (RBAC) and Attribute-Based (ABAC) access control
- High Performance - Redis caching for optimized response times
- API Documentation - Interactive Swagger/OpenAPI documentation
- Containerized - Docker and Docker Compose ready for any environment
- Type-Safe ORM - Drizzle ORM with full TypeScript support
- Input Validation - Zod schema validation for all endpoints
- Error Handling - Centralized error handling with structured responses
- Health Checks - Built-in health monitoring endpoints
- Graceful Shutdown - Proper cleanup of connections on termination
| Category | Technology |
|---|---|
| Runtime | Node.js 20+ |
| Language | TypeScript 5.9 |
| Framework | Express 5.x |
| Database | PostgreSQL 16 |
| ORM | Drizzle ORM |
| Cache | Redis 7 |
| Validation | Zod |
| Documentation | Swagger/OpenAPI |
| Containerization | Docker & Docker Compose |
| Package Manager | pnpm |
Ensure you have the following installed:
- Node.js >= 20.x (Download)
- pnpm >= 8.x (`npm install -g pnpm`)
- PostgreSQL >= 16 (Download)
- Redis >= 7 (Download)
- Docker (optional) (Download)
-
Clone the repository ```bash git clone https://github.com/shivamkarn1/Merchant-Hub-API.git cd Merchant-Hub-API ```
-
Install dependencies ```bash pnpm install ```
-
Create environment file ```bash cp .env.example .env ```
-
Configure environment variables ```env
NODE_ENV=development PORT=6767
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/merchant_hub
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-super-secret-key-change-in-production ```
-
Create the database ```bash createdb merchant_hub ```
-
Run migrations ```bash pnpm db:migrate ```
-
Generate migrations (for schema changes) ```bash pnpm db:generate ```
-
View database with Drizzle Studio ```bash pnpm db:studio ```
Development mode (with hot-reload): ```bash pnpm dev ```
Production mode: ```bash pnpm build pnpm start ```
The API will be available at `http://localhost:6767\`
Start all services with hot-reload enabled:
```bash
docker-compose -f docker-compose.dev.yml up -d
docker-compose -f docker-compose.dev.yml logs -f api
docker-compose -f docker-compose.dev.yml down ```
Optional: Enable Redis Commander for GUI access: ```bash docker-compose -f docker-compose.dev.yml --profile tools up -d
Access at http://localhost:8081
```
-
Build and start production services ```bash
docker-compose build
docker-compose up -d
docker-compose ps ```
-
Run migrations in container ```bash docker-compose exec api pnpm db:migrate ```
-
View logs ```bash docker-compose logs -f api ```
-
Stop and remove containers ```bash docker-compose down
docker-compose down -v ```
Docker Services:
| Service | Port | Description |
|---|---|---|
| `api` | 6767 | Main API application |
| `postgres` | 5432 | PostgreSQL database |
| `redis` | 6379 | Redis cache server |
Swagger UI is available at: ``` http://localhost:6767/api-docs ```
OpenAPI specification (JSON): ``` http://localhost:6767/api-docs.json ```
All protected endpoints require JWT authentication:
```http Authorization: Bearer <your_jwt_token> ```
User Roles:
| Role | Description | Permissions |
|---|---|---|
| `super_admin` | Full system access | All operations |
| `admin` | Administrative access | Manage all resources |
| `merchant` | Merchant-level access | Own resources only |
| `customer` | Customer-level access | Own data only |
| `viewer` | Read-only access | View resources |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| `GET` | `/api/v1/products/allProducts` | Get all products with filtering | β |
| `GET` | `/api/v1/products/allProducts/search` | Search products | β |
| `GET` | `/api/v1/products/:id` | Get product by ID | β |
| `POST` | `/api/v1/products/create` | Create new product | β |
| `PUT` | `/api/v1/products/update/:id` | Update product | β |
| `DELETE` | `/api/v1/products/delete/:id` | Delete product (soft) | β |
Query Parameters for GET /products/allProducts:
| Parameter | Type | Description |
|---|---|---|
| `q` | string | Search in name/description |
| `sku` | string | Filter by SKU |
| `minPrice` | number | Minimum price filter |
| `maxPrice` | number | Maximum price filter |
| `inStock` | boolean | Filter by stock availability |
| `sortBy` | string | Sort field (`price`, `name`, `created_at`) |
| `sortOrder` | string | Sort direction (`asc`, `desc`) |
| `limit` | number | Items per page (max: 100) |
| `offset` | number | Pagination offset |
| Method | Endpoint | Description | Auth | Permission |
|---|---|---|---|---|
| `GET` | `/api/v1/orders` | Get all orders (filtered by role) | β | `orders.read` |
| `GET` | `/api/v1/orders/:id` | Get order by ID | β | `orders.read` |
| `POST` | `/api/v1/orders/create` | Create new order | β | `orders.create` |
| `PUT` | `/api/v1/orders/:id/status` | Update order status | β | `orders.update` |
| `PUT` | `/api/v1/orders/:id/cancel` | Cancel order | β | `orders.cancel` |
```http GET /health ```
Response: ```json { "status": "healthy", "timestamp": "2025-11-26T10:30:00.000Z", "uptime": 3600, "version": "1.0.0" } ```
``` merchant-api/ βββ src/ β βββ app.ts # Express app configuration β βββ index.ts # Application entry point β βββ config/ β β βββ swagger.ts # Swagger/OpenAPI configuration β βββ controllers/ # Request handlers β β βββ orders/ β β β βββ orders.controller.ts β β βββ products/ β β βββ product.validation.ts β β βββ products.controller.ts β βββ db/ # Database layer β β βββ db.ts # Database connection β β βββ schema.ts # Combined schema exports β β βββ orders.schema.ts # Orders table schema β β βββ products.schema.ts # Products table schema β β βββ users.schema.ts # Users table schema β βββ middlewares/ # Express middlewares β β βββ abac.middleware.ts # Attribute-based access control β β βββ auth.middleware.ts # JWT authentication β β βββ errorHandler.ts # Global error handler β β βββ rbac.middleware.ts # Role-based access control β βββ routes/ # Route definitions β β βββ orders/ β β β βββ orders.routes.ts β β βββ products/ β β βββ products.routes.ts β βββ services/ # Business logic β β βββ orders/ β β β βββ orders.service.ts β β βββ products/ β β βββ products.service.ts β βββ types/ # TypeScript type definitions β β βββ auth.types.ts β β βββ express.d.ts β βββ utils/ # Utility functions β βββ ApiError.ts β βββ ApiResponse.ts β βββ asyncHandler.ts β βββ handleZodError.ts β βββ HttpStatusCodes.ts β βββ redis.ts # Redis client & caching βββ drizzle/ # Database migrations βββ docker-compose.yml # Production Docker setup βββ docker-compose.dev.yml # Development Docker setup βββ Dockerfile # Production Dockerfile βββ Dockerfile.dev # Development Dockerfile βββ drizzle.config.ts # Drizzle ORM configuration βββ package.json βββ tsconfig.json βββ README.md ```
``` βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ β users β β products β β orders β βββββββββββββββββββ€ βββββββββββββββββββ€ βββββββββββββββββββ€ β id β β id β β id β β email β β name β β order_number β β name β β description β β customer_id β β password_hash β β sku β β merchant_id β β role β β price β β status β β merchant_id β β stock β β total_amount β β parent_user_id β β merchant_id β β currency β β is_active β β created_by β β shipping_addr β β created_at β β created_at β β billing_addr β β updated_at β β updated_at β β created_at β βββββββββββββββββββ β deleted_at β β updated_at β βββββββββββββββββββ βββββββββββββββββββ β βΌ βββββββββββββββββββ β order_items β βββββββββββββββββββ€ β id β β order_id β β product_id β β quantity β β unit_price β β subtotal β β created_at β βββββββββββββββββββ ```
Redis caching is implemented with the following TTLs:
| Cache Type | TTL | Description |
|---|---|---|
| Product List | 2 min | Paginated product queries |
| Single Product | 5 min | Individual product details |
| Order List | 1 min | User-specific order lists |
| Single Order | 2 min | Individual order details |
Cache Invalidation:
- Product cache invalidated on create/update/delete
- Order cache invalidated on create/status update/cancel
- JWT Authentication - Stateless token-based authentication
- RBAC - Role-based permission system
- ABAC - Attribute-based resource access control
- Input Validation - Zod schema validation on all inputs
- SQL Injection Prevention - Parameterized queries via Drizzle ORM
- Security Headers - X-Content-Type-Options, X-Frame-Options, X-XSS-Protection
- Non-root Docker User - Container runs as unprivileged user
| Variable | Required | Default | Description |
|---|---|---|---|
| `NODE_ENV` | No | `development` | Environment mode |
| `PORT` | No | `6767` | Server port |
| `DATABASE_URL` | Yes | - | PostgreSQL connection string |
| `REDIS_URL` | No | `redis://localhost:6379` | Redis connection string |
| `JWT_SECRET` | Yes | - | JWT signing secret |
| `PGSSLMODE` | No | - | PostgreSQL SSL mode |
| Script | Description |
|---|---|
| `pnpm dev` | Start development server with hot-reload |
| `pnpm build` | Build TypeScript to JavaScript |
| `pnpm start` | Start production server |
| `pnpm db:generate` | Generate database migrations |
| `pnpm db:migrate` | Run database migrations |
| `pnpm db:studio` | Open Drizzle Studio GUI |
```bash
pnpm test ```
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch ```bash git checkout -b feature/amazing-feature ```
- Commit your changes ```bash git commit -m 'feat: add amazing feature' ```
- Push to the branch ```bash git push origin feature/amazing-feature ```
- Open a Pull Request
This project follows Conventional Commits:
- `feat:` - New features
- `fix:` - Bug fixes
- `docs:` - Documentation changes
- `style:` - Code style changes
- `refactor:` - Code refactoring
- `test:` - Test additions/changes
- `chore:` - Build process/auxiliary tools
This project is licensed under the ISC License - see the LICENSE file for details.
Made with β€οΈ by Shivam Karn
β Star this repository if you find it helpful!