Skip to content

cmelion/banking-api-assessment

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

75 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Banking API Assessment

Test Coverage TypeScript Node.js PostgreSQL Docker

A production-ready banking REST service built with AI-assisted development workflows. This project demonstrates modern banking operations including account management, secure transactions, money transfers, and comprehensive API documentation.

πŸ“‹ Table of Contents

πŸš€ Quick Start

Prerequisites

  • Node.js 18+ LTS
  • Docker & Docker Compose
  • Git

Installation

  1. Clone and setup

    git clone <repository-url>
    cd banking-api-assessment
    npm install
  2. Environment configuration

    cp .env.example .env
    # Edit .env with your configuration
  3. Start with Docker (Recommended)

    # Start PostgreSQL and Redis
    docker-compose up -d postgres redis
    
    # Run database migrations and seed data
    npm run db:migrate
    npm run db:seed
    
    # Start development server
    npm run dev
  4. Verify installation

    curl http://localhost:3000/health
    # Should return: {"status": "ok"}

Alternative: Full Docker Setup

# Start all services including the API
docker-compose up -d

# API will be available at http://localhost:3000
# Adminer (DB admin) at http://localhost:8080

Docker Services Provided

The Docker Compose configuration provides a complete containerized development environment:

Core Services:

  • banking-api - Main API server (port 3000) with health checks and auto-restart
  • postgres - PostgreSQL 16 database with persistent storage and health monitoring
  • redis - Redis cache/session store with persistent storage
  • adminer - Web-based database administration interface (port 8080)

Development Features:

  • banking-api-dev - Debug-enabled container for WebStorm development (port 3001, debug port 9229)
  • Custom networking - Isolated bridge network for service communication
  • Volume persistence - Data survives container restarts
  • Health monitoring - Comprehensive health checks ensure service reliability
  • Dependency management - Services start in correct order with health verification

Development Workflow Options:

  1. Hybrid Development (Recommended for active development):

    # Start only infrastructure services
    docker-compose up -d postgres redis adminer
    
    # Run API locally for hot reload
    npm run dev
  2. Full Docker Development:

    # Start everything including API
    docker-compose up -d
  3. Debug Mode (WebStorm/IDE debugging):

    # Start with debug profile
    docker-compose --profile dev up -d
    # API available at http://localhost:3001 with debug port 9229

πŸ› οΈ Technology Stack

Core Framework

  • Runtime: Node.js 18+ with TypeScript
  • Web Framework: Fastify (high-performance, schema validation)
  • Database: PostgreSQL (default) with SQLite option, Prisma ORM
  • Authentication: JWT with refresh tokens, Argon2id password hashing
  • Error Tracking: Optional Sentry integration for production monitoring

Development & Operations

  • Testing: Vitest with comprehensive coverage
  • Validation: JSON Schema with Fastify integration
  • Logging: Pino structured logging with correlation IDs
  • Containerization: Docker with multi-stage builds
  • Documentation: Swagger/OpenAPI integration

πŸ—οΈ Architecture

Project Structure

src/
β”œβ”€β”€ app.ts                 # Fastify application setup
β”œβ”€β”€ index.ts              # Server bootstrap
β”œβ”€β”€ config/               # Environment configuration
β”œβ”€β”€ db/                   # Database schema and utilities
β”œβ”€β”€ modules/              # Feature modules
β”‚   β”œβ”€β”€ auth/            # Authentication & authorization
β”‚   β”œβ”€β”€ users/           # User management
β”‚   β”œβ”€β”€ accounts/        # Account operations
β”‚   β”œβ”€β”€ transactions/    # Transaction processing
β”‚   β”œβ”€β”€ transfers/       # Money transfers
β”‚   β”œβ”€β”€ cards/           # Card management (mock)
β”‚   └── statements/      # Account statements
β”œβ”€β”€ plugins/             # Fastify plugins
└── lib/                 # Shared utilities

Database Schema

  • Users: Account holders with secure authentication
  • Accounts: Multi-currency accounts with balance tracking
  • Transactions: Immutable transaction ledger
  • Transfers: Atomic money transfers between accounts
  • Cards: Tokenized card management (PCI-compliant)
  • Statements: Generated account statements

πŸ“š API Documentation

Live Deployment

🌐 Production API: https://banking-api-assessment.vercel.app

πŸ–₯️ Banking Client: https://banking-client-nine.vercel.app (* use test@example.com/password123)

Demo Video:

Watch the video

Public Endpoints (no authentication required):

Base URL

  • Production: https://banking-api-assessment.vercel.app/api/v1
  • Development: http://localhost:3000/api/v1

API Documentation

⚠️ Security Note: Swagger documentation is enabled in production for ease of review. In a real production environment, API documentation should typically be disabled or secured to prevent information disclosure.

Core Endpoints

Authentication

POST /api/v1/auth/signup     # User registration
POST /api/v1/auth/login      # User authentication
POST /api/v1/auth/refresh    # Token refresh

User Management

GET    /api/v1/users/me      # Current user profile
PATCH  /api/v1/users/me      # Update profile

Account Operations

POST   /api/v1/accounts              # Create account
GET    /api/v1/accounts              # List user accounts
GET    /api/v1/accounts/:id          # Account details
GET    /api/v1/accounts/:id/transactions  # Transaction history

Transfers

POST   /api/v1/transfers             # Money transfer
# Supports Idempotency-Key header

Cards & Statements

POST   /api/v1/accounts/:id/cards    # Issue card (mock)
GET    /api/v1/accounts/:id/cards    # List cards (masked)
POST   /api/v1/accounts/:id/statements/generate  # Generate statement
GET    /api/v1/statements/:id        # Download statement

Health & Monitoring

GET    /health                       # Service health
GET    /ready                        # Readiness probe

Authentication

All protected endpoints require JWT authentication:

Authorization: Bearer <access_token>

Tokens are obtained via login and refreshed using refresh tokens for enhanced security.

πŸ’» Development

Available Scripts

Command Description
npm run dev Start development server with hot reload
npm run build Build TypeScript to production JavaScript
npm run start Start production server
npm test Run complete test suite
npm run test:watch Run tests in watch mode
npm run test:coverage Generate test coverage report
npm run lint Run ESLint code analysis
npm run format Format code with Prettier
npm run typecheck TypeScript compilation check

Database Operations

Command Description
npm run db:migrate Apply database migrations
npm run db:reset Reset database and apply seed data
npm run db:seed Populate database with test data
npm run db:generate Generate Prisma client
npm run db:use-sqlite Switch to SQLite configuration
npm run db:use-postgres Switch to PostgreSQL configuration
npm run test:sqlite Run tests with SQLite database

Docker Commands

Command Description
npm run docker:up Start all services with Docker
npm run docker:down Stop all Docker services
npm run docker:build Build application Docker image

Development Workflow

  1. Start development environment

    docker-compose up -d postgres redis
    npm run db:migrate
    npm run dev
  2. Make changes and test

    npm run test:watch    # Run tests in watch mode
    npm run lint          # Check code quality
  3. Database changes

    # Edit prisma/schema.prisma
    npm run db:migrate    # Generate migration
    npm run db:reset      # Reset with new schema

πŸ§ͺ Testing

Test Strategy

  • Unit Tests: Business logic, authentication, monetary calculations
  • Integration Tests: API endpoints with test database
  • Security Tests: Authentication flows, authorization checks
  • Current Coverage: 89.75% statement coverage βœ…
  • Coverage Target: 80%+ statement and branch coverage

Running Tests

# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Run specific test file
npx vitest src/modules/auth/auth.test.ts

# Run tests in watch mode
npm run test:watch

Coverage report:

Test Database

Tests can use either PostgreSQL or SQLite:

PostgreSQL (default):

  • Production-like environment
  • Full feature support
  • Docker-based setup

SQLite (optional):

# Switch to SQLite for lightweight testing
npm run db:use-sqlite
npm run test:sqlite

Benefits:

  • No Docker required
  • Faster test startup
  • Ideal for CI/CD environments

Tests are automatically:

  • Migrated before test runs
  • Seeded with test data
  • Isolated per test suite

Example Test Data

The seed script creates test users and accounts for development:

  • Test users with known credentials
  • Sample accounts with various balances
  • Transaction history for testing

πŸš€ Deployment

Docker Production

Multi-Stage Build Benefits

Our Docker configuration uses multi-stage builds for:

  • Reduced Image Size: 80% smaller production images (~150MB vs ~800MB)
  • Enhanced Security: No build tools or source code in production
  • Build Efficiency: Cached dependencies, parallel stage building
  • Clear Separation: Distinct build, test, and runtime environments
# Build production image
docker build -t banking-api .

# Run with docker-compose
docker-compose up -d

The production image:

  • Runs as non-root user
  • Contains only runtime dependencies
  • Includes health checks
  • Uses Alpine Linux for minimal attack surface

Environment Variables

Required environment variables (see .env.example):

# Application
NODE_ENV=production
PORT=3000

# Database
DATABASE_URL=postgresql://user:pass@host:5432/db
DIRECT_URL=postgresql://user:pass@host:5432/db

# JWT Secrets
JWT_SECRET=your-super-secret-jwt-key
JWT_REFRESH_SECRET=your-super-secret-refresh-key

# Optional
REDIS_URL=redis://localhost:6379
LOG_LEVEL=info

# External Error Tracking (Optional)
SENTRY_ENABLED=false
SENTRY_DSN=your-sentry-dsn
SENTRY_ENVIRONMENT=production

Vercel Deployment

This project is configured for Vercel deployment:

  1. Connect your repository to Vercel
  2. Add Vercel Postgres addon
  3. Set environment variables:
    • DATABASE_URL=${POSTGRES_PRISMA_URL}
    • DIRECT_URL=${POSTGRES_URL_NON_POOLING}
  4. Deploy automatically on push

Health Checks

The application provides comprehensive health monitoring:

  • Liveness: /health - Service is running
  • Readiness: /ready - Service can handle requests (includes DB connectivity)
  • Docker: Built-in container health checks

Monitoring & Observability

Built-in Features

  • Structured Logging: JSON logs with correlation IDs
  • Error Tracking: Centralized error handling with proper HTTP status codes
  • Performance: Request/response timing in logs
  • Security: Authentication events and suspicious activity logging

External Error Reporting (Sentry)

The application includes optional Sentry integration for production error tracking:

# Enable in production
SENTRY_ENABLED=true
SENTRY_DSN=https://your-dsn@sentry.io/project-id
SENTRY_ENVIRONMENT=production

Features:

  • Automatic error capture with context
  • Performance monitoring
  • User tracking (anonymized)
  • Sensitive data sanitization
  • Works with Sentry's free tier (5k errors/month)

πŸ”’ Security

Security Features

  • Password Security: Argon2id hashing with per-user salts
  • JWT Security: Short-lived access tokens with rotating refresh tokens
  • Input Validation: Comprehensive JSON schema validation
  • PCI Compliance: No raw card data storage, tokenized values only
  • Audit Trail: Complete transaction logging with user context
  • Rate Limiting: Protection against brute force attacks

Security Best Practices

  • Environment secrets never committed to repository
  • Sensitive data redacted from logs
  • HTTPS-only in production
  • Secure cookie settings
  • SQL injection prevention via Prisma ORM
  • CORS configuration for API access control

Known Security Considerations

  • Card operations are mocked for assessment purposes
  • Real implementation would require proper PCI DSS compliance
  • Additional rate limiting and fraud detection needed for production
  • Multi-factor authentication not implemented

See SECURITY.md for detailed security documentation.

🀝 Contributing

Development Guidelines

  1. Code Quality

    • TypeScript strict mode
    • ESLint and Prettier configuration
    • Comprehensive test coverage
    • Security-first approach
  2. Commit Standards

    • Meaningful commit messages
    • Document AI assistance usage
    • Frequent commits for iterative development
  3. Pull Request Process

    • All tests must pass
    • Code coverage maintained
    • Security review required
    • Documentation updated

AI Development Notes

This project was built using AI-assisted development:

  • See docs/AI_USAGE.md for detailed AI development log
  • Prompts, tools, and manual interventions documented
  • Challenges and solutions recorded for future reference

πŸ“– Additional Documentation

πŸ“ž Support

For questions or issues:

  1. Check the documentation in the docs/ directory
  2. Review test examples for usage patterns
  3. Check Docker logs: docker-compose logs banking-api
  4. Use the health endpoints to diagnose service issues

πŸ“„ License

This project is licensed under the ISC License - see the package.json file for details.


Built with ❀️ using AI-assisted development workflows.

About

Take-home test for the Software Engineer (Forward deployed) role.

Resources

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages