An open API service indexing awesome lists of open source software.

https://github.com/fdiskas/prices-microservice


https://github.com/fdiskas/prices-microservice

Last synced: 12 months ago
JSON representation

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! ๐Ÿš€**