{"id":29095021,"url":"https://github.com/fdiskas/prices-microservice","last_synced_at":"2025-07-09T07:34:15.714Z","repository":{"id":300525918,"uuid":"1004609767","full_name":"FDiskas/prices-microservice","owner":"FDiskas","description":null,"archived":false,"fork":false,"pushed_at":"2025-06-18T22:45:15.000Z","size":73,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-06-22T08:02:18.956Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/FDiskas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-18T22:45:11.000Z","updated_at":"2025-06-18T22:45:19.000Z","dependencies_parsed_at":"2025-06-22T08:02:20.811Z","dependency_job_id":"64c25a77-c418-4ad8-b288-96230e054e47","html_url":"https://github.com/FDiskas/prices-microservice","commit_stats":null,"previous_names":["fdiskas/prices-microservice"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/FDiskas/prices-microservice","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FDiskas%2Fprices-microservice","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FDiskas%2Fprices-microservice/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FDiskas%2Fprices-microservice/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FDiskas%2Fprices-microservice/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/FDiskas","download_url":"https://codeload.github.com/FDiskas/prices-microservice/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FDiskas%2Fprices-microservice/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262412211,"owners_count":23306875,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-06-28T10:06:38.520Z","updated_at":"2025-06-28T10:07:21.818Z","avatar_url":"https://github.com/FDiskas.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Prices API Microservice\n\nA high-performance microservice for product pricing with Euro currency support and quantity-based discounts, built with **Elysia**, **Bun**, and **Drizzle ORM**.\n\n## 🚀 Features\n\n- ✅ **Euro Currency Only** - All prices returned in EUR with proper localization\n- ✅ **Quantity-based Discounts** - Automatic discounts for bulk purchases with configurable rules\n- ✅ **Multiple Discount Tiers** - Flexible discount rules (quantity, percentage, fixed amount)\n- ✅ **Structured Response** - Returns value (float), ISO code, and localized string\n- ✅ **Drizzle ORM** - Type-safe database operations with schema migrations\n- ✅ **SQLite Database** - Fast, embedded database with foreign key constraints\n- ✅ **Auto Migrations** - Database schema versioning and automatic migrations\n- ✅ **Swagger Documentation** - Interactive API documentation at `/swagger`\n- ✅ **Health Monitoring** - Database connectivity and health check endpoint\n- ✅ **TypeScript** - Full type safety throughout the application\n- ✅ **CORS Support** - Configurable cross-origin resource sharing\n- ✅ **Input Validation** - Schema-based request/response validation\n- ✅ **Error Handling** - Centralized error handling with proper HTTP status codes\n- ✅ **Docker Support** - Multi-stage Docker builds for development and production\n- ✅ **Code Quality** - ESLint, Prettier, and TypeScript checks\n\n## 📁 Project Structure\n\n```\nsrc/\n├── config/           # Environment-based configuration management\n├── database/         # Database layer with Drizzle ORM\n│   ├── connection.ts     # Database connection and manager (singleton)\n│   ├── db.ts            # Database instance exports\n│   ├── schema.ts        # Drizzle table schemas and types\n│   ├── seeder.ts        # Database seeding utilities\n│   └── migrations/      # Drizzle migration files\n├── models/           # Repository pattern implementations\n│   ├── PriceRepository.ts      # Price data access layer\n│   ├── DiscountRuleRepository.ts # Discount rules data access\n│   └── repositories.ts         # Repository exports\n├── plugins/          # Elysia plugins and middleware\n│   ├── setup.ts         # Plugin configuration\n│   └── error-handler.ts # Centralized error handling\n├── routes/           # API route definitions\n│   ├── index.ts         # Route aggregation\n│   ├── health.ts        # Health check endpoints\n│   └── prices.ts        # Price-related endpoints\n├── schemas/          # Validation schemas\n│   └── price.ts         # Price request/response schemas\n├── services/         # Business logic layer\n│   ├── price.service.ts     # Price calculation logic\n│   └── price-service-new.ts # Enhanced price service\n├── tests/            # Test suites\n│   └── database-test.ts     # Database integration tests\n├── types/            # TypeScript type definitions\n│   ├── index.ts         # Common type exports\n│   ├── price.ts         # Price-related types\n│   └── database.ts      # Database-related types\n├── utils/            # Utility functions and helpers\n│   ├── index.ts         # Utility exports\n│   ├── errors.ts        # Custom error classes\n│   └── helpers.ts       # Helper functions\n└── index.ts          # Application entry point\n\ndata/                 # Database files\n├── prices.db        # SQLite database file\n\ndocker-compose.yml    # Production Docker configuration\ndocker-compose.dev.yml # Development Docker configuration\ndrizzle.config.ts     # Drizzle ORM configuration\neslint.config.mjs     # ESLint configuration\ntsconfig.json         # TypeScript configuration\ntest.rest            # REST client test file\n```\n\n## 🛠️ Getting Started\n\n### Prerequisites\n\n- [Bun](https://bun.sh/) v1.0+ installed on your system\n- [Docker](https://docker.com/) (optional, for containerized deployment)\n\n### Installation\n\n1. **Clone and install dependencies:**\n\n```bash\nbun install\n```\n\n2. **Set up environment (optional):**\n\n```bash\ncp .env.example .env\n# Edit .env with your preferred settings\n```\n\n3. **Run database migrations:**\n\n```bash\nbun run db:migrate\n```\n\n4. **Run the development server:**\n\n```bash\nbun run dev\n```\n\nThe API will be available at `http://localhost:3000`.\n\n### � Docker Development\n\n```bash\n# Start development environment\nbun run docker:dev\n\n# Start production environment\nbun run docker:prod\n\n# Stop containers\nbun run docker:stop\n```\n\n### �📊 Important Endpoints\n\n- **API Info:** `http://localhost:3000/`\n- **Health Check:** `http://localhost:3000/health`\n- **Swagger Documentation:** `http://localhost:3000/swagger`\n- **Drizzle Studio:** Run `bun run db:studio` for database management UI\n\n### Quick Test\n\nYou can test the API using the provided [test.rest](./test.rest) file or visit the Swagger documentation for an interactive experience.\n\n## 🔧 Development\n\n```bash\n# Development server with hot reload\nbun run dev\n\n# Production server\nbun run start\n\n# Database operations\nbun run db:generate    # Generate migration files\nbun run db:migrate     # Run migrations\nbun run db:studio      # Open Drizzle Studio\n\n# Code quality\nbun run type-check     # TypeScript type checking\nbun run lint           # Run ESLint with auto-fix\nbun run lint:check     # Check linting without fixing\nbun run format         # Format code with Prettier\nbun run format:check   # Check formatting without fixing\nbun run check-all      # Run all checks (type, lint, format)\nbun run fix-all        # Fix all issues (lint + format)\n\n# Build and deployment\nbun run build          # Build for production\nbun run clean          # Clean build files\n\n# Docker operations\nbun run docker:dev     # Start development containers\nbun run docker:prod    # Start production containers\nbun run docker:stop    # Stop all containers\n```\n\n## 🏗️ Architecture\n\n### **Modern Stack**\n\n- **[Elysia](https://elysiajs.com/)** - Fast and ergonomic web framework for Bun\n- **[Bun](https://bun.sh/)** - High-performance JavaScript runtime with built-in SQLite\n- **[Drizzle ORM](https://orm.drizzle.team/)** - Type-safe ORM with migrations and schema management\n- **[TypeScript](https://www.typescriptlang.org/)** - Full type safety and developer experience\n\n### **Design Patterns**\n\n- **Repository Pattern** - Data access abstraction with dedicated repository classes\n- **Singleton Pattern** - Database connection and service management\n- **Dependency Injection** - Clean service layer architecture\n- **Plugin Architecture** - Modular middleware system with Elysia plugins\n- **Schema-First API** - Type-safe request/response validation\n\n### **Database Layer**\n\n- **SQLite** - Embedded database with excellent performance\n- **Drizzle ORM** - Type-safe queries and schema management\n- **Migrations** - Version-controlled database schema changes\n- **Foreign Keys** - Referential integrity with cascade operations\n- **Indexing** - Optimized query performance\n\n### **Key Components**\n\n1. **Config Layer** - Environment-based configuration management\n2. **Database Layer** - Drizzle ORM with SQLite and migration support\n3. **Repository Layer** - Data access abstraction for prices and discount rules\n4. **Service Layer** - Business logic for price calculations and discount applications\n5. **Route Layer** - HTTP endpoint definitions with Elysia\n6. **Schema Layer** - Request/response validation with type safety\n7. **Plugin Layer** - Reusable middleware (CORS, Swagger, Error handling)\n8. **Types Layer** - Comprehensive TypeScript type definitions\n\n### **API Endpoints**\n\n- `GET /` - API information and version\n- `GET /health` - Health check with database connectivity\n- `GET /swagger` - Interactive API documentation\n- `GET /prices` - Get all prices with optional filtering\n- `GET /prices/:productId` - Get price for specific product\n- `POST /prices/calculate` - Calculate price with quantity and discounts\n- `POST /prices/batch` - Get prices for multiple products\n- `GET /prices/:productId/price` - Get detailed pricing information\n\n### **Best Practices Implemented**\n\n- ✅ **Type Safety** - Full TypeScript coverage with Drizzle ORM\n- ✅ **Input Validation** - Schema-based validation for all endpoints\n- ✅ **Error Handling** - Custom error classes and centralized handling\n- ✅ **Code Quality** - ESLint, Prettier, and automated formatting\n- ✅ **Database Integrity** - Foreign keys, constraints, and migrations\n- ✅ **Performance** - Database indexing and connection pooling\n- ✅ **Security** - Input sanitization and validation\n- ✅ **Documentation** - Auto-generated Swagger documentation\n- ✅ **Testing** - Database integration tests\n- ✅ **Containerization** - Multi-stage Docker builds\n- ✅ **Development Experience** - Hot reload and development tools\n\n## 🧪 Tech Stack\n\n### **Core Framework**\n- **[Elysia](https://elysiajs.com/)** - Fast and ergonomic web framework for Bun\n- **[Bun](https://bun.sh/)** - High-performance JavaScript runtime with built-in tooling\n\n### **Database \u0026 ORM**\n- **[Drizzle ORM](https://orm.drizzle.team/)** - Type-safe SQL ORM with migrations\n- **[Drizzle Kit](https://orm.drizzle.team/kit-docs/overview)** - Database migration and studio tools\n- **SQLite** - Embedded database via Bun's native support\n- **[@libsql/client](https://github.com/libsql/libsql-client-ts)** - Enhanced SQLite client\n\n### **API \u0026 Documentation**\n- **[@elysiajs/swagger](https://github.com/elysiajs/elysia-swagger)** - Auto-generated API documentation\n- **[@elysiajs/cors](https://github.com/elysiajs/elysia-cors)** - Cross-origin resource sharing\n\n### **Development Tools**\n- **TypeScript** - Type safety and enhanced developer experience\n- **ESLint** - Code linting with TypeScript support\n- **Prettier** - Code formatting and style consistency\n- **Docker** - Containerization for development and production\n\n### **Quality Assurance**\n- **TypeScript ESLint** - TypeScript-specific linting rules\n- **Stylistic ESLint Plugin** - Code style enforcement\n- **Rimraf** - Cross-platform file removal utility\n\n## 📊 Database\n\nThe SQLite database is managed by Drizzle ORM with the following features:\n\n### **Database Location**\n- **Development:** `./data/prices.db` (automatically created)\n- **Production:** Configurable via `DB_PATH` environment variable\n\n### **Schema Management**\n- **Drizzle Migrations** - Version-controlled schema changes\n- **Type Safety** - Generated TypeScript types from schema\n- **Foreign Keys** - Referential integrity with cascade operations\n- **Indexes** - Optimized query performance for price lookups\n\n### **Tables**\n- **`prices`** - Core pricing information for products\n  - Primary key: `id` (auto-increment)\n  - Unique constraint: `product_id`\n  - Default currency: EUR\n  - Timestamps: `created_at`, `updated_at`\n\n- **`discount_rules`** - Flexible discount configuration\n  - Linked to products via foreign key\n  - Rule types: quantity, percentage, fixed\n  - Quantity ranges: `min_quantity`, `max_quantity`\n  - Discount values: `discount_percentage`, `fixed_amount`\n\n### **Database Tools**\n- **Drizzle Studio** - Web-based database management UI (`bun run db:studio`)\n- **Migration Generation** - Automatic migration file creation (`bun run db:generate`)\n- **Migration Execution** - Safe database updates (`bun run db:migrate`)\n\n## 🌍 Environment Variables\n\n```bash\n# Server Configuration\nPORT=3000                    # Server port (default: 3000)\nHOSTNAME=localhost          # Server hostname (default: localhost)\n\n# Database Configuration  \nDB_PATH=./data/prices.db    # SQLite database file path\n\n# CORS Configuration\nCORS_ORIGIN=true           # CORS origin settings (default: true for all origins)\n```\n\nCreate a `.env` file in the project root with your preferred settings. All variables have sensible defaults and are optional.\n\n## 🤝 Contributing\n\n### **Development Workflow**\n\n1. **Follow the established architecture patterns**\n2. **Use TypeScript for all new code**\n3. **Add proper type definitions and exports**\n4. **Include validation schemas for new endpoints**\n5. **Update Swagger documentation annotations**\n6. **Add comprehensive error handling**\n7. **Write database migrations for schema changes**\n8. **Include integration tests for new features**\n\n### **Code Quality Standards**\n\n```bash\n# Before committing, ensure all checks pass:\nbun run check-all    # Type check + lint + format check\n\n# Or automatically fix issues:\nbun run fix-all      # Auto-fix lint and format issues\n```\n\n### **Database Changes**\n\n```bash\n# 1. Modify schema in src/database/schema.ts\n# 2. Generate migration files\nbun run db:generate\n\n# 3. Review generated migration files\n# 4. Apply migrations\nbun run db:migrate\n```\n\n### **Adding New Endpoints**\n\n1. Define route in `src/routes/`\n2. Add validation schema in `src/schemas/`\n3. Implement business logic in `src/services/`\n4. Add repository methods if needed in `src/models/`\n5. Update types in `src/types/`\n6. Add Swagger documentation\n7. Test with `test.rest` file\n\n---\n\n**Happy coding! 🚀**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffdiskas%2Fprices-microservice","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffdiskas%2Fprices-microservice","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffdiskas%2Fprices-microservice/lists"}