Skip to main content

Overview

Welcome to the Blackjack API project! This guide will help you understand the development workflow, coding standards, and best practices for contributing to this project.

Prerequisites

Before you begin, ensure you have the following installed:
  • Java 21 or higher
  • Maven 3.8+ (or use the included ./mvnw wrapper)
  • Docker & Docker Compose (for local database setup)
  • Git for version control
  • IDE (IntelliJ IDEA recommended)

Development Setup

1. Clone the Repository

git clone https://github.com/ccasro/5.01-Advanced-Spring-Framework.git
cd 5.01-Advanced-Spring-Framework

2. Start Local Databases

The project requires MongoDB and MySQL. Use Docker Compose to start both:
docker compose up -d
This will start:
  • MongoDB on localhost:27017
  • MySQL on localhost:3306

3. Run the Application

Start the Spring Boot application:
./mvnw spring-boot:run
The API will be available at http://localhost:8080

4. Verify Setup

Access the Swagger UI to verify the setup:
http://localhost:8080/swagger-ui.html

Project Structure

The project follows Hexagonal Architecture (Ports & Adapters) with clear separation of concerns:
src/main/java/cat/itacademy/s05/t01/blackjack_api/
├── domain/                    # Core business logic
│   ├── model/                # Domain entities and value objects
│   ├── port/                 # Repository and service interfaces
│   ├── service/              # Domain services
│   └── exception/            # Domain exceptions
├── application/               # Use cases and application logic
│   ├── usecase/              # Application use cases
│   ├── dto/                  # Application DTOs
│   └── mapper/               # Application mappers
└── infrastructure/            # External adapters
    ├── web/                  # REST controllers
    │   ├── controller/       # Controller classes
    │   ├── dto/              # Web request/response DTOs
    │   └── error/            # Global exception handling
    ├── persistence/          # Database adapters
    │   ├── mongo/            # MongoDB repositories
    │   └── mysql/            # MySQL repositories (R2DBC)
    └── config/               # Spring configuration

Architecture Principles

Domain Layer

  • Pure business logic
  • No framework dependencies
  • Defines ports (interfaces)
  • Contains aggregates and value objects

Application Layer

  • Orchestrates use cases
  • Coordinates domain objects
  • Transaction boundaries
  • Uses domain ports

Infrastructure Layer

  • Implements domain ports
  • Handles HTTP, database, external services
  • Framework-specific code
  • Configuration

Reactive Programming

  • Uses Spring WebFlux
  • Reactive MongoDB and R2DBC
  • Non-blocking operations
  • Returns Mono/Flux types

Coding Standards

Java Style

  • Java 21 language features are encouraged
  • Use Lombok for reducing boilerplate (@Data, @Builder, etc.)
  • Follow standard Java naming conventions
  • Keep methods small and focused (Single Responsibility)
  • Prefer immutability where possible

Domain-Driven Design

  • Game and Player are the main aggregates
  • Aggregates enforce business invariants
  • Use aggregate roots for external access
  • PlayerId, GameId, PlayerName, Card, Hand, etc.
  • Immutable and validated on creation
  • Represent domain concepts
  • Defined in domain/port/
  • Implemented in infrastructure/persistence/
  • Return reactive types (Mono, Flux)
  • One class per use case
  • Clear execute() method
  • Orchestrate domain logic

Reactive Patterns

All asynchronous operations use Project Reactor:
// Return Mono for single results
public Mono<GameStateResult> execute(String gameId) {
    return gameRepository.findById(gameId)
        .map(GameStateMapper::toResult);
}

// Return Flux for multiple results
public Flux<PlayerRankingDto> execute() {
    return playerRepository.findAllByOrderByScoreDesc();
}

Exception Handling

  • Domain exceptions (GameNotFoundException, InvalidMoveException, etc.) in domain/exception/
  • Global exception handler in infrastructure/web/error/GlobalExceptionHandler
  • Map domain exceptions to appropriate HTTP status codes

Development Workflow

Branch Strategy

Follow a feature branch workflow:
  1. main - Production-ready code
  2. feature/ - New features (feature/add-multiplayer)
  3. fix/ - Bug fixes (fix/dealer-bust-calculation)
  4. refactor/ - Code refactoring (refactor/simplify-game-logic)
  5. test/ - Test improvements (test/add-ranking-tests)
  6. docs/ - Documentation updates (docs/update-api-specs)

Creating a Feature

  1. Create a new branch from main:
git checkout main
git pull origin main
git checkout -b feature/your-feature-name
  1. Make your changes following the coding standards
  2. Write tests for your changes (see Testing Guide)
  3. Run tests locally:
./mvnw test
  1. Commit your changes using conventional commits

Commit Conventions

Follow Conventional Commits specification:

Commit Format

<type>: <description>

[optional body]

[optional footer]

Commit Types

TypeDescriptionExample
featNew featurefeat: add multiplayer support
fixBug fixfix: correct dealer bust detection
refactorCode refactoringrefactor: simplify Hand calculation
testAdd or update teststest: add integration tests for ranking
docsDocumentation changesdocs: update API documentation
styleCode style changesstyle: format code with prettier
perfPerformance improvementsperf: optimize card shuffling algorithm
choreMaintenance taskschore: update dependencies

Commit Examples

# Good commits
git commit -m "feat: add player statistics endpoint"
git commit -m "fix: prevent moves on finished games"
git commit -m "refactor: extract deck shuffling to domain service"
git commit -m "test: add unit tests for Hand value object"

# Bad commits (avoid these)
git commit -m "update"
git commit -m "fixes"
git commit -m "changes to game logic"

Commit Best Practices

  • Keep commits small and focused on a single change
  • Write clear and descriptive commit messages
  • Use present tense (“add” not “added”)
  • Reference issue numbers if applicable: fix: correct scoring (#42)
  • Do not commit:
    • Secrets or credentials
    • Compiled files (.class, target/)
    • IDE-specific files (use .gitignore)
    • Large binary files

Testing Requirements

All contributions must include appropriate tests:
  • Domain changes require domain unit tests
  • Use case changes require application tests with mocked repositories
  • Controller changes require WebTestClient integration tests
  • ✅ All tests must pass before submitting a pull request
Run tests before committing:
./mvnw test
See the Testing Guide for detailed testing guidelines.

Pull Request Process

1. Prepare Your Branch

Ensure your branch is up to date:
git checkout main
git pull origin main
git checkout your-branch
git rebase main

2. Create Pull Request

  • Push your branch to GitHub
  • Create a pull request against main
  • Use a descriptive PR title (following conventional commit format)
  • Provide a clear description of changes

PR Template

## Summary
Brief description of what this PR does

## Changes
- List of changes made
- New features or fixes

## Testing
- Describe how you tested the changes
- List any new tests added

## Related Issues
Closes #issue-number (if applicable)

3. Code Review

  • Address reviewer feedback
  • Keep the PR focused and small when possible
  • Use git commit --fixup for review changes if appropriate

4. Merge

Once approved:
  • Ensure all tests pass
  • Squash commits if needed
  • Merge to main

Database Migrations

MySQL schema changes use Flyway:
  1. Create a new migration file in src/main/resources/db/migration/
  2. Follow naming convention: V{version}__{description}.sql
    • Example: V2__add_player_statistics.sql
  3. Test migration locally:
./mvnw flyway:migrate

API Documentation

  • Keep Swagger/OpenAPI annotations up to date
  • Document all REST endpoints with @Operation, @ApiResponse
  • Test documentation at http://localhost:8080/swagger-ui.html

Code Review Guidelines

When reviewing code:
Check for adherence to hexagonal architecture
Verify domain logic is in the domain layer
Ensure tests cover the changes
Look for proper error handling
Verify reactive patterns are used correctly
Check commit messages follow conventions

Getting Help

If you need help:

Additional Resources

Testing Guide

Comprehensive testing strategy and examples

Architecture

Understand the hexagonal architecture

API Reference

Complete API documentation

GitHub Repository

View source code and issues

License

By contributing, you agree that your contributions will be licensed under the same license as the project.

Build docs developers (and LLMs) love