https://github.com/fdiskas/prices-microservice
https://github.com/fdiskas/prices-microservice
Last synced: 12 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/fdiskas/prices-microservice
- Owner: FDiskas
- Created: 2025-06-18T22:45:11.000Z (about 1 year ago)
- Default Branch: master
- Last Pushed: 2025-06-18T22:45:15.000Z (about 1 year ago)
- Last Synced: 2025-06-22T08:02:18.956Z (12 months ago)
- Language: TypeScript
- Size: 71.3 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Prices API Microservice
A high-performance microservice for product pricing with Euro currency support and quantity-based discounts, built with **Elysia**, **Bun**, and **Drizzle ORM**.
## ๐ Features
- โ
**Euro Currency Only** - All prices returned in EUR with proper localization
- โ
**Quantity-based Discounts** - Automatic discounts for bulk purchases with configurable rules
- โ
**Multiple Discount Tiers** - Flexible discount rules (quantity, percentage, fixed amount)
- โ
**Structured Response** - Returns value (float), ISO code, and localized string
- โ
**Drizzle ORM** - Type-safe database operations with schema migrations
- โ
**SQLite Database** - Fast, embedded database with foreign key constraints
- โ
**Auto Migrations** - Database schema versioning and automatic migrations
- โ
**Swagger Documentation** - Interactive API documentation at `/swagger`
- โ
**Health Monitoring** - Database connectivity and health check endpoint
- โ
**TypeScript** - Full type safety throughout the application
- โ
**CORS Support** - Configurable cross-origin resource sharing
- โ
**Input Validation** - Schema-based request/response validation
- โ
**Error Handling** - Centralized error handling with proper HTTP status codes
- โ
**Docker Support** - Multi-stage Docker builds for development and production
- โ
**Code Quality** - ESLint, Prettier, and TypeScript checks
## ๐ Project Structure
```
src/
โโโ config/ # Environment-based configuration management
โโโ database/ # Database layer with Drizzle ORM
โ โโโ connection.ts # Database connection and manager (singleton)
โ โโโ db.ts # Database instance exports
โ โโโ schema.ts # Drizzle table schemas and types
โ โโโ seeder.ts # Database seeding utilities
โ โโโ migrations/ # Drizzle migration files
โโโ models/ # Repository pattern implementations
โ โโโ PriceRepository.ts # Price data access layer
โ โโโ DiscountRuleRepository.ts # Discount rules data access
โ โโโ repositories.ts # Repository exports
โโโ plugins/ # Elysia plugins and middleware
โ โโโ setup.ts # Plugin configuration
โ โโโ error-handler.ts # Centralized error handling
โโโ routes/ # API route definitions
โ โโโ index.ts # Route aggregation
โ โโโ health.ts # Health check endpoints
โ โโโ prices.ts # Price-related endpoints
โโโ schemas/ # Validation schemas
โ โโโ price.ts # Price request/response schemas
โโโ services/ # Business logic layer
โ โโโ price.service.ts # Price calculation logic
โ โโโ price-service-new.ts # Enhanced price service
โโโ tests/ # Test suites
โ โโโ database-test.ts # Database integration tests
โโโ types/ # TypeScript type definitions
โ โโโ index.ts # Common type exports
โ โโโ price.ts # Price-related types
โ โโโ database.ts # Database-related types
โโโ utils/ # Utility functions and helpers
โ โโโ index.ts # Utility exports
โ โโโ errors.ts # Custom error classes
โ โโโ helpers.ts # Helper functions
โโโ index.ts # Application entry point
data/ # Database files
โโโ prices.db # SQLite database file
docker-compose.yml # Production Docker configuration
docker-compose.dev.yml # Development Docker configuration
drizzle.config.ts # Drizzle ORM configuration
eslint.config.mjs # ESLint configuration
tsconfig.json # TypeScript configuration
test.rest # REST client test file
```
## ๐ ๏ธ Getting Started
### Prerequisites
- [Bun](https://bun.sh/) v1.0+ installed on your system
- [Docker](https://docker.com/) (optional, for containerized deployment)
### Installation
1. **Clone and install dependencies:**
```bash
bun install
```
2. **Set up environment (optional):**
```bash
cp .env.example .env
# Edit .env with your preferred settings
```
3. **Run database migrations:**
```bash
bun run db:migrate
```
4. **Run the development server:**
```bash
bun run dev
```
The API will be available at `http://localhost:3000`.
### ๏ฟฝ Docker Development
```bash
# Start development environment
bun run docker:dev
# Start production environment
bun run docker:prod
# Stop containers
bun run docker:stop
```
### ๏ฟฝ๐ Important Endpoints
- **API Info:** `http://localhost:3000/`
- **Health Check:** `http://localhost:3000/health`
- **Swagger Documentation:** `http://localhost:3000/swagger`
- **Drizzle Studio:** Run `bun run db:studio` for database management UI
### Quick Test
You can test the API using the provided [test.rest](./test.rest) file or visit the Swagger documentation for an interactive experience.
## ๐ง Development
```bash
# Development server with hot reload
bun run dev
# Production server
bun run start
# Database operations
bun run db:generate # Generate migration files
bun run db:migrate # Run migrations
bun run db:studio # Open Drizzle Studio
# Code quality
bun run type-check # TypeScript type checking
bun run lint # Run ESLint with auto-fix
bun run lint:check # Check linting without fixing
bun run format # Format code with Prettier
bun run format:check # Check formatting without fixing
bun run check-all # Run all checks (type, lint, format)
bun run fix-all # Fix all issues (lint + format)
# Build and deployment
bun run build # Build for production
bun run clean # Clean build files
# Docker operations
bun run docker:dev # Start development containers
bun run docker:prod # Start production containers
bun run docker:stop # Stop all containers
```
## ๐๏ธ Architecture
### **Modern Stack**
- **[Elysia](https://elysiajs.com/)** - Fast and ergonomic web framework for Bun
- **[Bun](https://bun.sh/)** - High-performance JavaScript runtime with built-in SQLite
- **[Drizzle ORM](https://orm.drizzle.team/)** - Type-safe ORM with migrations and schema management
- **[TypeScript](https://www.typescriptlang.org/)** - Full type safety and developer experience
### **Design Patterns**
- **Repository Pattern** - Data access abstraction with dedicated repository classes
- **Singleton Pattern** - Database connection and service management
- **Dependency Injection** - Clean service layer architecture
- **Plugin Architecture** - Modular middleware system with Elysia plugins
- **Schema-First API** - Type-safe request/response validation
### **Database Layer**
- **SQLite** - Embedded database with excellent performance
- **Drizzle ORM** - Type-safe queries and schema management
- **Migrations** - Version-controlled database schema changes
- **Foreign Keys** - Referential integrity with cascade operations
- **Indexing** - Optimized query performance
### **Key Components**
1. **Config Layer** - Environment-based configuration management
2. **Database Layer** - Drizzle ORM with SQLite and migration support
3. **Repository Layer** - Data access abstraction for prices and discount rules
4. **Service Layer** - Business logic for price calculations and discount applications
5. **Route Layer** - HTTP endpoint definitions with Elysia
6. **Schema Layer** - Request/response validation with type safety
7. **Plugin Layer** - Reusable middleware (CORS, Swagger, Error handling)
8. **Types Layer** - Comprehensive TypeScript type definitions
### **API Endpoints**
- `GET /` - API information and version
- `GET /health` - Health check with database connectivity
- `GET /swagger` - Interactive API documentation
- `GET /prices` - Get all prices with optional filtering
- `GET /prices/:productId` - Get price for specific product
- `POST /prices/calculate` - Calculate price with quantity and discounts
- `POST /prices/batch` - Get prices for multiple products
- `GET /prices/:productId/price` - Get detailed pricing information
### **Best Practices Implemented**
- โ
**Type Safety** - Full TypeScript coverage with Drizzle ORM
- โ
**Input Validation** - Schema-based validation for all endpoints
- โ
**Error Handling** - Custom error classes and centralized handling
- โ
**Code Quality** - ESLint, Prettier, and automated formatting
- โ
**Database Integrity** - Foreign keys, constraints, and migrations
- โ
**Performance** - Database indexing and connection pooling
- โ
**Security** - Input sanitization and validation
- โ
**Documentation** - Auto-generated Swagger documentation
- โ
**Testing** - Database integration tests
- โ
**Containerization** - Multi-stage Docker builds
- โ
**Development Experience** - Hot reload and development tools
## ๐งช Tech Stack
### **Core Framework**
- **[Elysia](https://elysiajs.com/)** - Fast and ergonomic web framework for Bun
- **[Bun](https://bun.sh/)** - High-performance JavaScript runtime with built-in tooling
### **Database & ORM**
- **[Drizzle ORM](https://orm.drizzle.team/)** - Type-safe SQL ORM with migrations
- **[Drizzle Kit](https://orm.drizzle.team/kit-docs/overview)** - Database migration and studio tools
- **SQLite** - Embedded database via Bun's native support
- **[@libsql/client](https://github.com/libsql/libsql-client-ts)** - Enhanced SQLite client
### **API & Documentation**
- **[@elysiajs/swagger](https://github.com/elysiajs/elysia-swagger)** - Auto-generated API documentation
- **[@elysiajs/cors](https://github.com/elysiajs/elysia-cors)** - Cross-origin resource sharing
### **Development Tools**
- **TypeScript** - Type safety and enhanced developer experience
- **ESLint** - Code linting with TypeScript support
- **Prettier** - Code formatting and style consistency
- **Docker** - Containerization for development and production
### **Quality Assurance**
- **TypeScript ESLint** - TypeScript-specific linting rules
- **Stylistic ESLint Plugin** - Code style enforcement
- **Rimraf** - Cross-platform file removal utility
## ๐ Database
The SQLite database is managed by Drizzle ORM with the following features:
### **Database Location**
- **Development:** `./data/prices.db` (automatically created)
- **Production:** Configurable via `DB_PATH` environment variable
### **Schema Management**
- **Drizzle Migrations** - Version-controlled schema changes
- **Type Safety** - Generated TypeScript types from schema
- **Foreign Keys** - Referential integrity with cascade operations
- **Indexes** - Optimized query performance for price lookups
### **Tables**
- **`prices`** - Core pricing information for products
- Primary key: `id` (auto-increment)
- Unique constraint: `product_id`
- Default currency: EUR
- Timestamps: `created_at`, `updated_at`
- **`discount_rules`** - Flexible discount configuration
- Linked to products via foreign key
- Rule types: quantity, percentage, fixed
- Quantity ranges: `min_quantity`, `max_quantity`
- Discount values: `discount_percentage`, `fixed_amount`
### **Database Tools**
- **Drizzle Studio** - Web-based database management UI (`bun run db:studio`)
- **Migration Generation** - Automatic migration file creation (`bun run db:generate`)
- **Migration Execution** - Safe database updates (`bun run db:migrate`)
## ๐ Environment Variables
```bash
# Server Configuration
PORT=3000 # Server port (default: 3000)
HOSTNAME=localhost # Server hostname (default: localhost)
# Database Configuration
DB_PATH=./data/prices.db # SQLite database file path
# CORS Configuration
CORS_ORIGIN=true # CORS origin settings (default: true for all origins)
```
Create a `.env` file in the project root with your preferred settings. All variables have sensible defaults and are optional.
## ๐ค Contributing
### **Development Workflow**
1. **Follow the established architecture patterns**
2. **Use TypeScript for all new code**
3. **Add proper type definitions and exports**
4. **Include validation schemas for new endpoints**
5. **Update Swagger documentation annotations**
6. **Add comprehensive error handling**
7. **Write database migrations for schema changes**
8. **Include integration tests for new features**
### **Code Quality Standards**
```bash
# Before committing, ensure all checks pass:
bun run check-all # Type check + lint + format check
# Or automatically fix issues:
bun run fix-all # Auto-fix lint and format issues
```
### **Database Changes**
```bash
# 1. Modify schema in src/database/schema.ts
# 2. Generate migration files
bun run db:generate
# 3. Review generated migration files
# 4. Apply migrations
bun run db:migrate
```
### **Adding New Endpoints**
1. Define route in `src/routes/`
2. Add validation schema in `src/schemas/`
3. Implement business logic in `src/services/`
4. Add repository methods if needed in `src/models/`
5. Update types in `src/types/`
6. Add Swagger documentation
7. Test with `test.rest` file
---
**Happy coding! ๐**