Skip to content

Latest commit

 

History

History
286 lines (200 loc) · 9.02 KB

File metadata and controls

286 lines (200 loc) · 9.02 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Development Guidelines

Code Quality Standards

  • Scalability: Write code that handles growth in data, users, and complexity
  • Best Practices: Follow industry standards and proven patterns
  • Performance: Optimize for speed and efficiency; consider database query performance, caching, and algorithmic complexity
  • Modern Standards: Use current TypeScript/JavaScript features, latest framework patterns, and contemporary architecture

Commit Workflow

IMPORTANT: Always stage, commit, push, and open PRs directly — do not provide commands for the user to run manually. Use the Bash tool to execute all git operations.

Format requirements:

  • First line: conventional commit type (feat/fix/docs/test/refactor/perf/chore)
  • Add blank lines between sections for readability
  • Group related changes with bullet points
  • No attribution or AI-generated notices

Attribution

  • Never include AI attribution in code, comments, or commit messages
  • Never add "Generated by Claude" or similar notices
  • Code should appear as if written by a human developer

Project Overview

Station is a pnpm workspace monorepo for gaming guild/organization management with a NestJS backend and React frontend. The architecture uses role-based access control (RBAC) with flexible JSONB permissions, JWT authentication with refresh token rotation, and Redis caching with graceful in-memory fallback.

Essential Commands

Development

# Start both frontend and backend (from root)
pnpm dev

# Start individual services (from root)
pnpm dev:backend   # NestJS on http://localhost:3001
pnpm dev:frontend  # React on http://localhost:5173

# Start infrastructure
docker-compose up -d  # PostgreSQL (5433) + Redis (6379)

Database & Migrations

# From backend/ directory
pnpm migration:create src/migrations/YourMigrationName
pnpm migration:run       # Run pending migrations
pnpm migration:revert    # Rollback last migration
pnpm db:backup           # Create timestamped backup
pnpm db:health-check     # Validate database state
pnpm seed                # Seed database with test data

Critical: Always create backup before production migrations. See backend/docs/database/migrations.md for complete migration safety procedures including rollback decision tree and pre-migration checklist.

Testing

# Backend tests (from backend/)
pnpm test              # Unit tests
pnpm test:e2e          # E2E tests (requires database)
pnpm test:watch        # Watch mode
pnpm test:cov          # Coverage report

# From root (all packages)
pnpm test

Note: E2E tests require PostgreSQL running. Use docker-compose up -d database first.

Code Quality

pnpm lint              # Lint all packages
pnpm format            # Format with Prettier
pnpm typecheck         # TypeScript type checking
pnpm build             # Build all packages

Architecture

Backend Module Structure

NestJS follows modular architecture where each feature is self-contained:

  • auth - JWT authentication, refresh tokens, password reset
  • users - User management with extended profiles
  • organizations - Guild/organization CRUD
  • roles - Role definitions with JSONB permissions
  • user-organization-roles - Many-to-many user ↔ org ↔ role relationships
  • permissions - Permission aggregation with Redis caching
  • audit-logs - Activity tracking and audit trails

Key Pattern: Each module contains:

  • *.module.ts - Module definition with imports/providers
  • *.controller.ts - HTTP endpoints (REST API)
  • *.service.ts - Business logic
  • *.entity.ts - TypeORM database entities
  • dto/ - Data transfer objects with class-validator
  • *.guard.ts - Route protection (JWT, permissions)

Database Architecture

TypeORM with PostgreSQL using manual migrations (not synchronize in production):

users ─┐
       ├─ user_organization_role ─┬─ organizations
roles ─┘                          │
                                  └─ audit_log
refresh_tokens ── users
password_resets ── users

Critical Details:

  • Test environment uses synchronize: true and dropSchema: true (auto-recreates schema)
  • Production uses migrations only: migrationsRun: false (manual execution required)
  • Composite indexes on user_organization_role for query performance
  • JSONB permissions field on role enables flexible permission structures

Caching Strategy

Redis with automatic fallback:

  • Default: Redis connection at REDIS_HOST:6379
  • Fallback: In-memory cache if Redis unavailable
  • Test env: Forced in-memory via USE_REDIS_CACHE=false
  • TTL: 5 minutes (300000ms)

Cached entities: Organization members, aggregated permissions

Authentication Flow

  1. Register: POST /auth/register → Creates user with hashed password
  2. Login: POST /auth/login → Returns access_token (15min) + refresh_token (7 days)
  3. Protected Routes: Add header Authorization: Bearer <access_token>
  4. Refresh: POST /auth/refresh with refresh token → New token pair
  5. Logout: POST /auth/logout → Revokes refresh token

Security:

  • Passwords hashed with bcrypt (10 rounds)
  • Refresh token rotation (old tokens revoked)
  • JWT signed with JWT_SECRET from environment
  • Guards: JwtAuthGuard, LocalAuthGuard, RefreshTokenAuthGuard

Environment Configuration

Backend (.env)

Required variables:

DATABASE_HOST=localhost
DATABASE_PORT=5433
DATABASE_USER=stationDbUser
DATABASE_PASSWORD=stationDbPassword1
DATABASE_NAME=stationDb
JWT_SECRET=your-secret-key
REDIS_HOST=localhost
REDIS_PORT=6379
PORT=3001
APP_NAME=STATION BACKEND
USE_REDIS_CACHE=true  # Set false for tests

Test Environment (.env.test)

Same as .env but with USE_REDIS_CACHE=false to avoid Redis dependency in CI/CD.

Special Considerations

Migration Safety

Every production migration must:

  1. Have working up() and down() methods
  2. Be tested with migration:revert in development
  3. Include pre-migration backup: pnpm db:backup
  4. Run post-migration health check: pnpm db:health-check
  5. Follow checklist in backend/src/migrations/templates/PRE_MIGRATION_CHECKLIST.md

Templates: Use backend/src/migrations/templates/migration-template.ts for structure and examples.

Rollback decision tree available in backend/docs/database/migrations.md - includes 5-step process for handling failures.

Test Database Behavior

  • E2E tests drop and recreate schema on every run (via dropSchema: true)
  • Tests run serially (--runInBand) to avoid race conditions
  • Database must be running: docker-compose up -d database
  • Some tests skip in CI/CD if PostgreSQL tools (pg_dump, psql) unavailable

Husky & Pre-commit Hooks

lint-staged runs on commit:

  • Backend: ESLint + Prettier
  • Root: Prettier on JSON/MD files

If hooks fail, fix issues and re-commit. To bypass (not recommended): git commit --no-verify

Monorepo Tooling

Turbo manages builds/tests across packages:

  • Parallel execution where possible
  • Caching for faster rebuilds
  • Run from root to execute across all packages
  • Use pnpm --filter <package> for specific packages

API Documentation

Swagger UI auto-generated at http://localhost:3001/api/docs when backend running.

Includes:

  • All endpoints with request/response schemas
  • Bearer token authentication
  • Try-it-out functionality

Common Gotchas

  1. Database not running: Start with docker-compose up -d database before running app or tests
  2. Migration errors: Always test rollback in dev: pnpm migration:revert
  3. Test failures in CI: Check if test requires PostgreSQL tools (backup/health-check tests skip in CI)
  4. Redis connection warnings: Expected in test environment - app falls back to memory cache
  5. Port conflicts: Backend default is 3001, frontend is 5173, PostgreSQL is 5433 (not 5432)
  6. pnpm version: Requires pnpm 8+ (specified in package.json engines)
  7. Node version: Requires Node 18+ (specified in package.json engines)

Project-Specific Patterns

Error Handling

Controllers use NestJS built-in exceptions:

throw new NotFoundException('User not found');
throw new BadRequestException('Invalid input');
throw new UnauthorizedException('Invalid credentials');

DTO Validation

All DTOs use class-validator decorators:

@IsString()
@IsNotEmpty()
username: string;

@IsEmail()
email: string;

Global ValidationPipe in main.ts auto-validates incoming requests.

Permission Checking

Use PermissionsService.getUserPermissions(userId, orgId) to get aggregated permissions from all user's roles in an organization. Results are cached in Redis.

Audit Logging

AuditLogsService tracks important actions. Log via:

await this.auditLogsService.log({
  userId,
  action: 'USER_UPDATED',
  resource: 'User',
  resourceId: user.id,
  metadata: { changes: ... }
});