mirror of
https://github.com/alirezarezvani/ClaudeForge.git
synced 2026-07-03 02:13:15 -04:00
Initial commit: ClaudeForge v1.0.0
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
# CLAUDE.md Reference Examples
|
||||
|
||||
This folder contains reference implementations of CLAUDE.md files for different project types and team sizes.
|
||||
|
||||
**✨ NEW**: All examples now follow **100% native Claude Code format** with proper project structure diagrams, setup instructions, architecture sections, and file structure explanations - matching the official `/update-claude-md` slash command format.
|
||||
|
||||
## Available Examples
|
||||
|
||||
### By Complexity Level
|
||||
|
||||
| Example | Lines | Team Size | Use Case |
|
||||
|---------|-------|-----------|----------|
|
||||
| `minimal-solo-CLAUDE.md` | ~75 | Solo | Prototypes, hackathons, quick projects |
|
||||
| `core-small-team-CLAUDE.md` | ~175 | Small (5) | MVPs, small team projects |
|
||||
| `modular-root-CLAUDE.md` | ~150 | Medium (12) | Full-stack production apps (root file) |
|
||||
| `python-api-CLAUDE.md` | ~225 | Small (6) | Python FastAPI backend projects |
|
||||
|
||||
### By Project Type
|
||||
|
||||
| Example | Project Type | Tech Stack |
|
||||
|---------|--------------|------------|
|
||||
| `minimal-solo-CLAUDE.md` | Web App Prototype | TypeScript, React, Node |
|
||||
| `core-small-team-CLAUDE.md` | Web Application MVP | React, Node, PostgreSQL |
|
||||
| `python-api-CLAUDE.md` | Backend API | Python, FastAPI, PostgreSQL |
|
||||
| `modular-root-CLAUDE.md` | Full-Stack App (root) | React, Node, PostgreSQL |
|
||||
| `modular-backend-CLAUDE.md` | Backend (context-specific) | Node, Express, PostgreSQL |
|
||||
| `modular-frontend-CLAUDE.md` | Frontend (context-specific) | React, TypeScript, Tailwind |
|
||||
|
||||
## Modular Architecture Examples
|
||||
|
||||
For projects with multiple major components, use separate CLAUDE.md files:
|
||||
|
||||
**Root Navigation Hub**:
|
||||
- `modular-root-CLAUDE.md` - Root file with navigation (~150 lines)
|
||||
|
||||
**Context-Specific Files**:
|
||||
- `modular-backend-CLAUDE.md` - Backend guidelines (~200 lines)
|
||||
- `modular-frontend-CLAUDE.md` - Frontend guidelines (~225 lines)
|
||||
|
||||
## How to Use These Examples
|
||||
|
||||
### 1. Starting a New Project
|
||||
|
||||
```bash
|
||||
# Copy appropriate template to your project
|
||||
cp examples/core-small-team-CLAUDE.md /path/to/your/project/CLAUDE.md
|
||||
|
||||
# Customize for your tech stack and workflows
|
||||
```
|
||||
|
||||
### 2. Setting Up Modular Architecture
|
||||
|
||||
```bash
|
||||
# Copy root file to project root
|
||||
cp examples/modular-root-CLAUDE.md /path/to/your/project/CLAUDE.md
|
||||
|
||||
# Copy context-specific files to subdirectories
|
||||
cp examples/modular-backend-CLAUDE.md /path/to/your/project/backend/CLAUDE.md
|
||||
cp examples/modular-frontend-CLAUDE.md /path/to/your/project/frontend/CLAUDE.md
|
||||
```
|
||||
|
||||
### 3. Using with claude-md-enhancer Skill
|
||||
|
||||
These examples demonstrate the output quality you can expect from the skill:
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill.
|
||||
Can you create a CLAUDE.md similar to the core-small-team example
|
||||
but customized for my Go API project?
|
||||
```
|
||||
|
||||
## Template Selection Guide
|
||||
|
||||
### Choose Minimal Template When:
|
||||
- Solo developer
|
||||
- Prototype or proof-of-concept
|
||||
- Hackathon or time-boxed project
|
||||
- Need quick setup with minimal guidance
|
||||
|
||||
### Choose Core Template When:
|
||||
- Small team (2-10 developers)
|
||||
- MVP or early-stage product
|
||||
- Standard web application
|
||||
- Need comprehensive but concise guidelines
|
||||
|
||||
### Choose Modular Architecture When:
|
||||
- Medium/large team (10+ developers)
|
||||
- Full-stack or complex application
|
||||
- Multiple major components (frontend, backend, database, etc.)
|
||||
- Production or enterprise environment
|
||||
|
||||
### Choose Tech-Specific Template When:
|
||||
- Specific tech stack (Python/FastAPI, Go, etc.)
|
||||
- Team needs stack-specific best practices
|
||||
- Want language-specific examples and patterns
|
||||
|
||||
## Quality Metrics
|
||||
|
||||
### Native Format Sections (100% Compliance)
|
||||
|
||||
All examples now include these **native Claude Code sections**:
|
||||
|
||||
- ✅ **Overview** - Concise project description
|
||||
- ✅ **Project Structure** - ASCII tree diagram showing folder hierarchy
|
||||
- ✅ **File Structure** - Detailed explanations of directories and their purpose
|
||||
- ✅ **Setup & Installation** - Step-by-step setup commands
|
||||
- ✅ **Architecture** - System architecture and component flow (for complex projects)
|
||||
- ✅ **Core Principles** - Development philosophies and standards
|
||||
- ✅ **Tech Stack** - Technologies with versions
|
||||
- ✅ **Development Workflow** - Step-by-step development process
|
||||
- ✅ **Testing Requirements** - Testing strategy and coverage targets
|
||||
- ✅ **Error Handling** - Error handling patterns and best practices
|
||||
- ✅ **Common Commands** - Frequently used commands with descriptions
|
||||
|
||||
**Why This Matters**: These sections match the official `/update-claude-md` slash command format, ensuring Claude Code can navigate and understand your codebase efficiently.
|
||||
|
||||
### Expected Quality Scores
|
||||
|
||||
| Example | Quality Score |
|
||||
|---------|---------------|
|
||||
| `minimal-solo-CLAUDE.md` | 70-75/100 |
|
||||
| `core-small-team-CLAUDE.md` | 85-90/100 |
|
||||
| `modular-root-CLAUDE.md` | 80-85/100 |
|
||||
| `modular-backend-CLAUDE.md` | 90-95/100 |
|
||||
| `modular-frontend-CLAUDE.md` | 90-95/100 |
|
||||
| `python-api-CLAUDE.md` | 85-90/100 |
|
||||
|
||||
## Customization Tips
|
||||
|
||||
1. **Update Tech Stack**: Replace technologies with your actual stack
|
||||
2. **Adjust Workflows**: Modify development process to match your team
|
||||
3. **Add Team Standards**: Include team-specific conventions
|
||||
4. **Update Commands**: Replace commands with your actual npm/yarn/poetry scripts
|
||||
5. **Add Context**: Include project-specific context that helps Claude understand your goals
|
||||
|
||||
## Contributing
|
||||
|
||||
These examples represent best practices as of November 2025. If you have improvements or additional examples, please contribute them!
|
||||
@@ -0,0 +1,183 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance for Claude Code when working with this project.
|
||||
|
||||
## Overview
|
||||
|
||||
Full-stack web application built with React, Node.js, and PostgreSQL. Small team (5 developers) following TDD and code review practices for MVP development.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project-root/
|
||||
├── client/
|
||||
│ ├── src/
|
||||
│ │ ├── components/ # React components
|
||||
│ │ ├── pages/ # Page components
|
||||
│ │ ├── hooks/ # Custom hooks
|
||||
│ │ ├── services/ # API client services
|
||||
│ │ └── utils/ # Utility functions
|
||||
│ ├── public/ # Static assets
|
||||
│ └── package.json
|
||||
├── server/
|
||||
│ ├── src/
|
||||
│ │ ├── controllers/ # Route handlers
|
||||
│ │ ├── services/ # Business logic
|
||||
│ │ ├── models/ # Database models
|
||||
│ │ ├── middleware/ # Express middleware
|
||||
│ │ └── routes/ # API routes
|
||||
│ ├── tests/ # Server tests
|
||||
│ └── package.json
|
||||
├── database/
|
||||
│ ├── migrations/ # Database migrations
|
||||
│ └── seeds/ # Seed data
|
||||
├── docker-compose.yml
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
- **client/** - React frontend application
|
||||
- **src/components/** - Reusable UI components
|
||||
- **src/pages/** - Route-level page components
|
||||
- **src/services/** - API client functions
|
||||
- **server/** - Node.js backend API
|
||||
- **src/controllers/** - Request handlers and route logic
|
||||
- **src/services/** - Business logic layer
|
||||
- **src/models/** - Database models and schemas
|
||||
- **src/middleware/** - Express middleware (auth, validation, logging)
|
||||
- **database/** - Database migrations and seed data
|
||||
|
||||
## Architecture
|
||||
|
||||
**Stack**: React SPA + Express API + PostgreSQL
|
||||
|
||||
**Flow**: Client → Express API → PostgreSQL
|
||||
- Frontend: React SPA with client-side routing
|
||||
- Backend: RESTful API with Express
|
||||
- Database: PostgreSQL with migration-based schema management
|
||||
- Communication: JSON over HTTP/HTTPS
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies for both client and server
|
||||
npm install
|
||||
cd client && npm install
|
||||
cd ../server && npm install
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with your database credentials and API keys
|
||||
|
||||
# Start PostgreSQL (using Docker)
|
||||
docker-compose up -d postgres
|
||||
|
||||
# Run database migrations
|
||||
cd server && npm run migrate
|
||||
|
||||
# Seed database with initial data
|
||||
npm run seed
|
||||
|
||||
# Start development servers
|
||||
npm run dev # Starts both client and server
|
||||
```
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Test-Driven Development**: Write tests before implementation
|
||||
2. **Code Quality**: Maintain high standards with clean, readable code
|
||||
3. **Documentation**: Keep docs in sync with code changes
|
||||
4. **Collaboration**: Clear communication and code reviews
|
||||
5. **Performance**: Consider performance implications early
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Frontend**: React 18, TypeScript 5, Tailwind CSS
|
||||
- **Backend**: Node.js 20, Express 4, TypeScript
|
||||
- **Database**: PostgreSQL 15, Prisma ORM
|
||||
- **Testing**: Jest, React Testing Library, Supertest
|
||||
- **Build**: Vite, Docker, GitHub Actions
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Development Process
|
||||
|
||||
1. Create feature branch from `main`: `git checkout -b feature/name`
|
||||
2. Write tests first (TDD approach)
|
||||
3. Implement feature with proper error handling
|
||||
4. Run linter and tests locally: `npm run lint && npm test`
|
||||
5. Create pull request with description
|
||||
6. Code review (minimum 1 approval required)
|
||||
7. Merge to main (auto-deploy to staging)
|
||||
|
||||
### Testing Requirements
|
||||
|
||||
- Unit tests for all business logic
|
||||
- Integration tests for API endpoints
|
||||
- E2E tests for critical user flows
|
||||
- Minimum 80% code coverage
|
||||
- All tests must pass before merge
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Use try-catch blocks for async operations
|
||||
- Log errors with context (user ID, request ID, timestamp)
|
||||
- Return meaningful error messages to clients
|
||||
- Never expose stack traces in production
|
||||
- Implement global error handling middleware
|
||||
|
||||
## Code Review Checklist
|
||||
|
||||
Before requesting review, ensure:
|
||||
|
||||
- [ ] Tests written and passing (80%+ coverage)
|
||||
- [ ] No console.log or debugger statements
|
||||
- [ ] Error handling implemented properly
|
||||
- [ ] Documentation updated (README, API docs)
|
||||
- [ ] No hardcoded values (use environment variables)
|
||||
- [ ] TypeScript types defined (no `any` types)
|
||||
- [ ] Performance considerations addressed
|
||||
- [ ] Security best practices followed
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev # Start both client and server
|
||||
npm run dev:client # Start client only
|
||||
npm run dev:server # Start server only
|
||||
npm test # Run all tests
|
||||
npm run test:watch # Run tests in watch mode
|
||||
npm run lint # Run ESLint
|
||||
npm run format # Format code with Prettier
|
||||
|
||||
# Production
|
||||
npm run build # Build client and server
|
||||
npm run start # Start production servers
|
||||
|
||||
# Database
|
||||
npm run migrate # Run database migrations
|
||||
npm run migrate:rollback # Rollback last migration
|
||||
npm run seed # Seed database with test data
|
||||
npm run db:reset # Reset database (dev only)
|
||||
|
||||
# Docker
|
||||
docker-compose up # Start all services
|
||||
docker-compose down # Stop all services
|
||||
docker-compose logs -f # View logs
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
|
||||
API endpoints are documented using Swagger/OpenAPI. After starting the server, visit:
|
||||
|
||||
```
|
||||
http://localhost:3000/api-docs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Project Type**: Web Application (MVP)
|
||||
**Team Size**: Small (5 developers)
|
||||
**Lines**: ~175 (Core template with native format)
|
||||
@@ -0,0 +1,80 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Quick guidance for this prototype project.
|
||||
|
||||
## Overview
|
||||
|
||||
Rapid prototyping project using TypeScript, React, and Node.js. Focus on speed and iteration over production-readiness.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project-root/
|
||||
├── src/
|
||||
│ ├── components/ # React components
|
||||
│ ├── pages/ # Page components
|
||||
│ ├── hooks/ # Custom hooks
|
||||
│ └── utils/ # Utility functions
|
||||
├── public/ # Static assets
|
||||
├── tests/ # Test files
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
- **src/components/** - Reusable UI components
|
||||
- **src/pages/** - Route-level page components
|
||||
- **src/hooks/** - Custom React hooks for shared logic
|
||||
- **src/utils/** - Helper functions and utilities
|
||||
- **tests/** - Unit and integration tests
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Start development server
|
||||
npm run dev
|
||||
|
||||
# Run tests
|
||||
npm test
|
||||
```
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Move Fast**: Prioritize speed over perfection
|
||||
2. **Keep It Simple**: Avoid unnecessary complexity
|
||||
3. **Iterate Quickly**: Test and refine rapidly
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Frontend**: TypeScript, React
|
||||
- **Backend**: Node.js, Express
|
||||
- **Build**: Vite
|
||||
- **Testing**: Jest, React Testing Library
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. Create feature branch: `git checkout -b feature/name`
|
||||
2. Implement and test locally
|
||||
3. Commit changes: `git commit -m "Add feature"`
|
||||
4. Push to remote: `git push`
|
||||
5. Deploy to staging for testing
|
||||
|
||||
## Quick Commands
|
||||
|
||||
```bash
|
||||
npm run dev # Start development server
|
||||
npm test # Run all tests
|
||||
npm run build # Build for production
|
||||
npm run lint # Check code quality
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Project Type**: Prototype
|
||||
**Team Size**: Solo
|
||||
**Lines**: ~75 (Minimal template with native format)
|
||||
@@ -0,0 +1,345 @@
|
||||
# Backend Development Guidelines
|
||||
|
||||
This file provides guidance for backend development in this project.
|
||||
|
||||
## Overview
|
||||
|
||||
Express API backend with TypeScript, PostgreSQL database, and Redis caching. RESTful API design with comprehensive error handling, testing, and security practices.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
backend/
|
||||
├── src/
|
||||
│ ├── controllers/ # Route handlers
|
||||
│ │ ├── auth.controller.ts
|
||||
│ │ ├── user.controller.ts
|
||||
│ │ └── product.controller.ts
|
||||
│ ├── services/ # Business logic
|
||||
│ │ ├── auth.service.ts
|
||||
│ │ ├── user.service.ts
|
||||
│ │ └── product.service.ts
|
||||
│ ├── models/ # Database models
|
||||
│ │ ├── User.ts
|
||||
│ │ └── Product.ts
|
||||
│ ├── middleware/ # Express middleware
|
||||
│ │ ├── auth.middleware.ts
|
||||
│ │ ├── validation.middleware.ts
|
||||
│ │ └── error.middleware.ts
|
||||
│ ├── routes/ # Route definitions
|
||||
│ │ ├── auth.routes.ts
|
||||
│ │ ├── user.routes.ts
|
||||
│ │ └── product.routes.ts
|
||||
│ ├── utils/ # Utilities
|
||||
│ │ ├── logger.ts
|
||||
│ │ ├── validators.ts
|
||||
│ │ └── crypto.ts
|
||||
│ ├── config/ # Configuration
|
||||
│ │ ├── database.ts
|
||||
│ │ └── redis.ts
|
||||
│ └── index.ts # App entry point
|
||||
├── tests/
|
||||
│ ├── unit/ # Unit tests
|
||||
│ ├── integration/ # Integration tests
|
||||
│ └── fixtures/ # Test data
|
||||
├── prisma/
|
||||
│ ├── schema.prisma # Database schema
|
||||
│ └── migrations/ # Migration files
|
||||
├── .env.example
|
||||
├── package.json
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
- **controllers/** - Handle HTTP requests, validate input, call services
|
||||
- **services/** - Business logic layer, independent of HTTP
|
||||
- **models/** - Database models and Prisma client usage
|
||||
- **middleware/** - Express middleware (auth, validation, logging, errors)
|
||||
- **routes/** - Route definitions mapping URLs to controllers
|
||||
- **utils/** - Shared utility functions (logging, validation, crypto)
|
||||
- **config/** - Configuration files for database, Redis, etc.
|
||||
- **tests/** - Unit and integration tests
|
||||
|
||||
## Architecture
|
||||
|
||||
**Layer Pattern**: Controllers → Services → Models → Database
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
HTTP Request → Route → Middleware → Controller → Service → Model → Database
|
||||
↓
|
||||
Response
|
||||
```
|
||||
|
||||
**Components**:
|
||||
- **Controllers**: HTTP layer, request/response handling
|
||||
- **Services**: Business logic, reusable across controllers
|
||||
- **Models**: Data access layer with Prisma ORM
|
||||
- **Middleware**: Cross-cutting concerns (auth, logging, validation)
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with:
|
||||
# - DATABASE_URL (PostgreSQL connection string)
|
||||
# - REDIS_URL (Redis connection string)
|
||||
# - JWT_SECRET (secret for token signing)
|
||||
# - PORT (default 3000)
|
||||
|
||||
# Start PostgreSQL and Redis (using Docker)
|
||||
docker-compose up -d postgres redis
|
||||
|
||||
# Run database migrations
|
||||
npx prisma migrate dev
|
||||
|
||||
# Generate Prisma client
|
||||
npx prisma generate
|
||||
|
||||
# Seed database
|
||||
npm run seed
|
||||
|
||||
# Start development server
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## API Design
|
||||
|
||||
### RESTful Conventions
|
||||
|
||||
- Use RESTful conventions for API endpoints
|
||||
- Implement proper HTTP status codes:
|
||||
- `200 OK` - Successful GET/PUT/PATCH
|
||||
- `201 Created` - Successful POST
|
||||
- `204 No Content` - Successful DELETE
|
||||
- `400 Bad Request` - Validation error
|
||||
- `401 Unauthorized` - Authentication required
|
||||
- `403 Forbidden` - Insufficient permissions
|
||||
- `404 Not Found` - Resource not found
|
||||
- `500 Internal Server Error` - Server error
|
||||
|
||||
### Versioning
|
||||
|
||||
- Version APIs when breaking changes are needed
|
||||
- Format: `/api/v1/`, `/api/v2/`
|
||||
- Example: `/api/v1/users`, `/api/v2/users`
|
||||
|
||||
### Documentation
|
||||
|
||||
- Document all endpoints with OpenAPI/Swagger
|
||||
- Access docs at `/api-docs` when server running
|
||||
- Include request/response examples
|
||||
- Document authentication requirements
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
- Use camelCase for JSON keys
|
||||
- Use snake_case for database columns
|
||||
- Use kebab-case for URL paths
|
||||
|
||||
## Database Operations
|
||||
|
||||
### Migrations
|
||||
|
||||
- Use migrations for all schema changes
|
||||
- **Never edit existing migrations** - create new ones
|
||||
- Test migrations on copy of production data
|
||||
- Include both up and down migrations
|
||||
- Name migrations descriptively: `20250112_add_user_email_index`
|
||||
|
||||
### Query Optimization
|
||||
|
||||
- Implement proper indexes for frequently queried columns
|
||||
- Avoid N+1 queries - use joins or batch loading with Prisma `include`
|
||||
- Use `EXPLAIN ANALYZE` to analyze slow queries
|
||||
- Paginate large result sets (max 100 items per page)
|
||||
|
||||
### Transactions
|
||||
|
||||
- Use transactions for multi-step operations
|
||||
- Example:
|
||||
```typescript
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({ ... });
|
||||
await tx.account.create({ ... });
|
||||
});
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Global Error Middleware
|
||||
|
||||
- Implement global error handling middleware
|
||||
- Catch all errors in one place
|
||||
- Log errors with context (request ID, user ID, timestamp)
|
||||
|
||||
### Error Response Format
|
||||
|
||||
Return consistent error response format:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "VALIDATION_ERROR",
|
||||
"message": "User-friendly message",
|
||||
"details": [
|
||||
{
|
||||
"field": "email",
|
||||
"message": "Invalid email format"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Error Classes
|
||||
|
||||
- Use custom error classes for different error types
|
||||
- Examples: `ValidationError`, `AuthenticationError`, `NotFoundError`
|
||||
- Never expose stack traces to clients in production
|
||||
- Log full stack traces server-side
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- Write unit tests for business logic (services, utils)
|
||||
- Mock external dependencies (database, APIs, Redis)
|
||||
- Test edge cases and error conditions
|
||||
- Aim for 80%+ code coverage
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- Write integration tests for API endpoints
|
||||
- Test full request/response cycle
|
||||
- Use test database (separate from dev/prod)
|
||||
- Reset database state between tests
|
||||
|
||||
### Best Practices
|
||||
|
||||
- Use test databases, never production
|
||||
- Use factories/fixtures for test data
|
||||
- Test authentication and authorization
|
||||
- Test error scenarios
|
||||
|
||||
```bash
|
||||
# Run tests
|
||||
npm test # All tests
|
||||
npm run test:unit # Unit tests only
|
||||
npm run test:integration # Integration tests only
|
||||
npm run test:coverage # With coverage report
|
||||
```
|
||||
|
||||
## Security Practices
|
||||
|
||||
### Input Validation
|
||||
|
||||
- Validate all input data with validation middleware
|
||||
- Use schema validation (Joi, Zod, class-validator)
|
||||
- Sanitize user input to prevent XSS
|
||||
|
||||
### Database Security
|
||||
|
||||
- Use parameterized queries (Prisma handles this)
|
||||
- Prevents SQL injection
|
||||
- Never concatenate user input into queries
|
||||
|
||||
### Authentication & Authorization
|
||||
|
||||
- Hash passwords with bcrypt (minimum 10 rounds)
|
||||
- Use JWT for stateless authentication
|
||||
- Implement refresh token rotation
|
||||
- Use environment variables for secrets
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
- Implement rate limiting on public endpoints
|
||||
- Example: 100 requests per 15 minutes per IP
|
||||
- Protect against brute force attacks
|
||||
|
||||
### CORS
|
||||
|
||||
- Implement proper CORS policies
|
||||
- Whitelist allowed origins
|
||||
- Don't use wildcard (`*`) in production
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Caching
|
||||
|
||||
- Implement caching for frequently accessed data
|
||||
- Use Redis for session storage and data caching
|
||||
- Cache expensive computations
|
||||
- Set appropriate TTL (time-to-live)
|
||||
|
||||
### Database
|
||||
|
||||
- Use database connection pooling (Prisma handles this)
|
||||
- Optimize queries with proper indexes
|
||||
- Monitor slow queries
|
||||
- Use read replicas for heavy read workloads
|
||||
|
||||
### Async Operations
|
||||
|
||||
- Use async/await for I/O operations
|
||||
- Never block the event loop
|
||||
- Use worker threads for CPU-intensive tasks
|
||||
- Queue background jobs with RabbitMQ/Bull
|
||||
|
||||
## Logging
|
||||
|
||||
- Use structured logging (Winston, Pino)
|
||||
- Log levels: ERROR, WARN, INFO, DEBUG
|
||||
- Include context: request ID, user ID, timestamp
|
||||
- Never log sensitive data (passwords, tokens)
|
||||
- Rotate log files in production
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev # Start dev server with hot reload
|
||||
npm test # Run all tests
|
||||
npm run test:watch # Run tests in watch mode
|
||||
npm run lint # Run ESLint
|
||||
npm run format # Format code with Prettier
|
||||
|
||||
# Database
|
||||
npm run migrate # Run migrations
|
||||
npm run migrate:rollback # Rollback last migration
|
||||
npm run migrate:reset # Reset database (dev only)
|
||||
npm run seed # Seed database with test data
|
||||
npx prisma studio # Open Prisma Studio (DB GUI)
|
||||
|
||||
# Production
|
||||
npm run build # Build TypeScript
|
||||
npm start # Start production server
|
||||
|
||||
# Debugging
|
||||
npm run dev:debug # Start with debugger
|
||||
npm run logs # View application logs
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
|
||||
After starting the server, access API documentation at:
|
||||
|
||||
```
|
||||
http://localhost:3000/api-docs
|
||||
```
|
||||
|
||||
Swagger UI provides interactive API documentation with:
|
||||
- All endpoints listed
|
||||
- Request/response schemas
|
||||
- Try-it-out functionality
|
||||
- Authentication examples
|
||||
|
||||
---
|
||||
|
||||
**Context**: Backend (Node.js/Express/TypeScript/PostgreSQL)
|
||||
**Lines**: ~200 (Backend-specific template with native format)
|
||||
@@ -0,0 +1,385 @@
|
||||
# Frontend Development Guidelines
|
||||
|
||||
This file provides guidance for frontend development in this project.
|
||||
|
||||
## Overview
|
||||
|
||||
React 18 SPA with TypeScript, Tailwind CSS, and React Query for server state. Component-based architecture with hooks, performance optimization, and comprehensive testing.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
frontend/
|
||||
├── src/
|
||||
│ ├── components/ # Reusable components
|
||||
│ │ ├── common/ # Shared UI components
|
||||
│ │ │ ├── Button.tsx
|
||||
│ │ │ ├── Input.tsx
|
||||
│ │ │ └── Modal.tsx
|
||||
│ │ ├── layout/ # Layout components
|
||||
│ │ │ ├── Header.tsx
|
||||
│ │ │ ├── Footer.tsx
|
||||
│ │ │ └── Sidebar.tsx
|
||||
│ │ └── features/ # Feature-specific components
|
||||
│ │ ├── UserList.tsx
|
||||
│ │ └── ProductCard.tsx
|
||||
│ ├── pages/ # Page components (routes)
|
||||
│ │ ├── HomePage.tsx
|
||||
│ │ ├── UserPage.tsx
|
||||
│ │ └── NotFoundPage.tsx
|
||||
│ ├── hooks/ # Custom React hooks
|
||||
│ │ ├── useAuth.ts
|
||||
│ │ ├── useUser.ts
|
||||
│ │ └── useLocalStorage.ts
|
||||
│ ├── store/ # State management
|
||||
│ │ ├── AuthContext.tsx
|
||||
│ │ └── ThemeContext.tsx
|
||||
│ ├── services/ # API client functions
|
||||
│ │ ├── api.ts
|
||||
│ │ ├── auth.service.ts
|
||||
│ │ └── user.service.ts
|
||||
│ ├── utils/ # Utility functions
|
||||
│ │ ├── formatters.ts
|
||||
│ │ ├── validators.ts
|
||||
│ │ └── constants.ts
|
||||
│ ├── styles/ # Global styles
|
||||
│ │ └── global.css
|
||||
│ ├── types/ # TypeScript types
|
||||
│ │ ├── user.types.ts
|
||||
│ │ └── api.types.ts
|
||||
│ ├── App.tsx # Root component
|
||||
│ ├── main.tsx # Entry point
|
||||
│ └── router.tsx # Route definitions
|
||||
├── public/ # Static assets
|
||||
│ ├── images/
|
||||
│ ├── fonts/
|
||||
│ └── favicon.ico
|
||||
├── tests/
|
||||
│ ├── unit/ # Unit tests
|
||||
│ ├── integration/ # Integration tests
|
||||
│ └── e2e/ # End-to-end tests
|
||||
├── .env.example
|
||||
├── package.json
|
||||
├── vite.config.ts
|
||||
├── tailwind.config.js
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
- **components/** - Reusable UI components
|
||||
- **common/** - Shared components (Button, Input, Modal)
|
||||
- **layout/** - Layout components (Header, Footer, Sidebar)
|
||||
- **features/** - Feature-specific components
|
||||
- **pages/** - Page-level components mapped to routes
|
||||
- **hooks/** - Custom React hooks for shared logic
|
||||
- **store/** - Context providers for global state (auth, theme)
|
||||
- **services/** - API client functions and HTTP calls
|
||||
- **utils/** - Helper functions, formatters, validators
|
||||
- **types/** - TypeScript type definitions and interfaces
|
||||
|
||||
## Architecture
|
||||
|
||||
**Component Hierarchy**: App → Router → Pages → Features → Common
|
||||
|
||||
**State Management**:
|
||||
- **Local State**: `useState` for component-specific state
|
||||
- **Global State**: Context API for auth, theme, user
|
||||
- **Server State**: React Query for API data caching
|
||||
- **Form State**: React Hook Form for complex forms
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
User Action → Component → Service → API → React Query Cache → Component Update
|
||||
```
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with:
|
||||
# - VITE_API_URL (backend API URL)
|
||||
# - VITE_ENV (development/staging/production)
|
||||
|
||||
# Start development server
|
||||
npm run dev
|
||||
|
||||
# Server runs at http://localhost:5173
|
||||
```
|
||||
|
||||
## Component Standards
|
||||
|
||||
### Functional Components with Hooks
|
||||
|
||||
- Prefer functional components with hooks over class components
|
||||
- Use TypeScript for all components
|
||||
- Keep components small and focused (< 200 lines)
|
||||
- Extract reusable logic into custom hooks
|
||||
- Use composition over inheritance
|
||||
|
||||
### Component Structure
|
||||
|
||||
```typescript
|
||||
interface Props {
|
||||
userId: string;
|
||||
onUpdate?: () => void;
|
||||
}
|
||||
|
||||
export function UserProfile({ userId, onUpdate }: Props) {
|
||||
// 1. Hooks first
|
||||
const { data, loading, error } = useUserData(userId);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
|
||||
// 2. Event handlers
|
||||
const handleEdit = () => setIsEditing(true);
|
||||
|
||||
// 3. Early returns
|
||||
if (loading) return <Spinner />;
|
||||
if (error) return <ErrorMessage error={error} />;
|
||||
|
||||
// 4. Main render
|
||||
return <div>{/* component JSX */}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### TypeScript Best Practices
|
||||
|
||||
- Define interfaces for all props
|
||||
- Use `type` for unions and primitives
|
||||
- Avoid `any` - use `unknown` if truly dynamic
|
||||
- Export types alongside components
|
||||
|
||||
## State Management
|
||||
|
||||
### Local State
|
||||
|
||||
- Keep component state local when possible
|
||||
- Use `useState` for simple values
|
||||
- Use `useReducer` for complex state logic
|
||||
|
||||
### Global State (Context API)
|
||||
|
||||
- Use Context API for app-wide state (theme, auth, user)
|
||||
- Example: AuthContext, ThemeContext
|
||||
- Avoid overuse - not for all shared state
|
||||
|
||||
### Server State (React Query)
|
||||
|
||||
- Use React Query for server state management
|
||||
- Automatic caching, refetching, and updates
|
||||
- Example:
|
||||
```typescript
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['users', userId],
|
||||
queryFn: () => fetchUser(userId)
|
||||
});
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
|
||||
- Avoid prop drilling - use context for deep state
|
||||
- Document state shape and update patterns
|
||||
- Keep state as close to usage as possible
|
||||
|
||||
## Styling Guidelines
|
||||
|
||||
### Tailwind CSS
|
||||
|
||||
- Use Tailwind CSS utility classes
|
||||
- Create reusable component classes in `tailwind.config.js`
|
||||
- Avoid inline styles except for truly dynamic values
|
||||
- Use CSS variables for theming in `global.css`
|
||||
|
||||
### Responsive Design
|
||||
|
||||
- Ensure responsive design for all breakpoints (mobile-first)
|
||||
- Breakpoints: `sm:` (640px), `md:` (768px), `lg:` (1024px), `xl:` (1280px)
|
||||
- Test on mobile, tablet, desktop
|
||||
|
||||
### Dark Mode
|
||||
|
||||
- Implement dark mode with `dark:` variant
|
||||
- Use CSS variables for theme colors
|
||||
- Respect user's system preference
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Code Splitting
|
||||
|
||||
- Lazy load routes with `React.lazy()` and `Suspense`
|
||||
- Lazy load heavy components (charts, editors, modals)
|
||||
- Example:
|
||||
```typescript
|
||||
const Dashboard = lazy(() => import('./pages/Dashboard'));
|
||||
```
|
||||
|
||||
### Image Optimization
|
||||
|
||||
- Optimize images (use WebP, AVIF formats)
|
||||
- Use lazy loading with `loading="lazy"` attribute
|
||||
- Serve responsive images with `srcset`
|
||||
|
||||
### Bundle Optimization
|
||||
|
||||
- Minimize bundle size - analyze with `npm run analyze`
|
||||
- Use tree-shaking (import only what you need)
|
||||
- Avoid importing entire libraries
|
||||
|
||||
### React Optimization
|
||||
|
||||
- Use `useMemo` for expensive calculations
|
||||
- Use `useCallback` for function props
|
||||
- Use `React.memo` for expensive components
|
||||
- Avoid unnecessary re-renders
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- Write unit tests for utility functions
|
||||
- Test business logic separately from UI
|
||||
- Mock external dependencies
|
||||
- Aim for 80%+ code coverage
|
||||
|
||||
### Component Tests
|
||||
|
||||
- Write component tests with React Testing Library
|
||||
- Test user interactions, not implementation details
|
||||
- Test accessibility (keyboard, screen readers)
|
||||
- Example:
|
||||
```typescript
|
||||
test('renders user profile', () => {
|
||||
render(<UserProfile userId="123" />);
|
||||
expect(screen.getByText(/profile/i)).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
### API Mocking
|
||||
|
||||
- Mock API calls with MSW (Mock Service Worker)
|
||||
- Create realistic mock responses
|
||||
- Test loading and error states
|
||||
|
||||
### E2E Tests
|
||||
|
||||
- Write E2E tests with Playwright for critical flows
|
||||
- Test complete user journeys
|
||||
- Run E2E tests in CI/CD
|
||||
|
||||
```bash
|
||||
# Run tests
|
||||
npm test # All tests
|
||||
npm run test:unit # Unit tests only
|
||||
npm run test:e2e # E2E tests with Playwright
|
||||
npm run test:coverage # With coverage report
|
||||
```
|
||||
|
||||
## Accessibility (a11y)
|
||||
|
||||
### Semantic HTML
|
||||
|
||||
- Use semantic HTML elements (`<button>`, `<nav>`, `<main>`, `<article>`)
|
||||
- Don't use `<div>` for interactive elements
|
||||
- Use proper heading hierarchy (`<h1>` → `<h2>` → `<h3>`)
|
||||
|
||||
### Keyboard Navigation
|
||||
|
||||
- Ensure keyboard navigation works
|
||||
- Test with Tab, Enter, Escape keys
|
||||
- Add focus styles (don't remove outline)
|
||||
|
||||
### ARIA Labels
|
||||
|
||||
- Add ARIA labels where needed
|
||||
- Use `aria-label`, `aria-labelledby`, `aria-describedby`
|
||||
- Test with screen readers (VoiceOver, NVDA)
|
||||
|
||||
### Color Contrast
|
||||
|
||||
- Maintain color contrast ratios (WCAG AA minimum 4.5:1)
|
||||
- Test with browser DevTools accessibility panel
|
||||
- Don't rely on color alone to convey information
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Error Boundaries
|
||||
|
||||
- Use Error Boundaries for component errors
|
||||
- Implement fallback UI
|
||||
- Log errors to monitoring service (Sentry)
|
||||
|
||||
### User-Friendly Messages
|
||||
|
||||
- Show user-friendly error messages
|
||||
- Avoid technical jargon
|
||||
- Provide actionable next steps
|
||||
|
||||
### Async Error Handling
|
||||
|
||||
- Handle loading and error states in all async operations
|
||||
- Example:
|
||||
```typescript
|
||||
if (isLoading) return <Spinner />;
|
||||
if (error) return <ErrorMessage error={error} />;
|
||||
```
|
||||
|
||||
## Custom Hooks Pattern
|
||||
|
||||
Create custom hooks for reusable logic:
|
||||
|
||||
```typescript
|
||||
function useUserData(userId: string) {
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUserData(userId)
|
||||
.then(setData)
|
||||
.catch(setError)
|
||||
.finally(() => setLoading(false));
|
||||
}, [userId]);
|
||||
|
||||
return { data, loading, error };
|
||||
}
|
||||
```
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev # Start dev server (http://localhost:5173)
|
||||
npm test # Run all tests
|
||||
npm run test:watch # Run tests in watch mode
|
||||
npm run lint # Run ESLint
|
||||
npm run type-check # TypeScript check
|
||||
npm run format # Format code with Prettier
|
||||
|
||||
# Production
|
||||
npm run build # Build for production
|
||||
npm run preview # Preview production build locally
|
||||
npm run analyze # Analyze bundle size
|
||||
|
||||
# Testing
|
||||
npm run test:unit # Unit tests only
|
||||
npm run test:e2e # E2E tests with Playwright
|
||||
npm run test:coverage # Coverage report
|
||||
```
|
||||
|
||||
## Development Best Practices
|
||||
|
||||
- **Component Organization**: One component per file
|
||||
- **Naming**: PascalCase for components, camelCase for functions/variables
|
||||
- **Props**: Destructure props in function signature
|
||||
- **Imports**: Group imports (React, libraries, local)
|
||||
- **Comments**: Write comments for complex logic only
|
||||
- **Console Logs**: Remove before committing
|
||||
|
||||
---
|
||||
|
||||
**Context**: Frontend (React/TypeScript/Tailwind)
|
||||
**Lines**: ~225 (Frontend-specific template with native format)
|
||||
@@ -0,0 +1,192 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides top-level guidance for Claude Code when working with this full-stack project.
|
||||
|
||||
## Overview
|
||||
|
||||
Full-stack application with separated backend API and frontend SPA. Uses modular CLAUDE.md architecture with context-specific files for detailed guidance. Medium team (12 developers) in production phase.
|
||||
|
||||
## Quick Navigation
|
||||
|
||||
- [Backend Guidelines](backend/CLAUDE.md) - API, services, database operations
|
||||
- [Frontend Guidelines](frontend/CLAUDE.md) - Components, state management, styling
|
||||
- [Database Operations](database/CLAUDE.md) - Schemas, migrations, query optimization
|
||||
- [CI/CD Workflows](.github/CLAUDE.md) - Automation, testing, deployments
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project-root/
|
||||
├── backend/
|
||||
│ ├── src/
|
||||
│ │ ├── controllers/ # API route handlers
|
||||
│ │ ├── services/ # Business logic
|
||||
│ │ ├── models/ # Database models
|
||||
│ │ ├── middleware/ # Express middleware
|
||||
│ │ └── utils/ # Shared utilities
|
||||
│ ├── tests/ # Backend tests
|
||||
│ └── CLAUDE.md # Backend-specific guidance
|
||||
├── frontend/
|
||||
│ ├── src/
|
||||
│ │ ├── components/ # React components
|
||||
│ │ ├── pages/ # Page components
|
||||
│ │ ├── hooks/ # Custom hooks
|
||||
│ │ ├── store/ # State management
|
||||
│ │ └── styles/ # CSS/styling
|
||||
│ ├── public/ # Static assets
|
||||
│ └── CLAUDE.md # Frontend-specific guidance
|
||||
├── database/
|
||||
│ ├── migrations/ # Schema migrations
|
||||
│ ├── seeds/ # Seed data
|
||||
│ └── CLAUDE.md # Database guidance
|
||||
├── .github/
|
||||
│ ├── workflows/ # CI/CD workflows
|
||||
│ └── CLAUDE.md # CI/CD guidance
|
||||
├── docker-compose.yml
|
||||
├── package.json
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
This project uses **modular architecture** with context-specific CLAUDE.md files:
|
||||
|
||||
- **backend/** - Express API server
|
||||
- See [backend/CLAUDE.md](backend/CLAUDE.md) for API design, error handling, testing
|
||||
- **frontend/** - React SPA
|
||||
- See [frontend/CLAUDE.md](frontend/CLAUDE.md) for component standards, state, styling
|
||||
- **database/** - PostgreSQL database
|
||||
- See [database/CLAUDE.md](database/CLAUDE.md) for migrations, schemas, queries
|
||||
- **.github/** - CI/CD workflows
|
||||
- See [.github/CLAUDE.md](.github/CLAUDE.md) for deployment, automation
|
||||
|
||||
## Architecture
|
||||
|
||||
**Stack**: React SPA + Express API + PostgreSQL + Redis Cache
|
||||
|
||||
**Services**:
|
||||
- Frontend: React 18 with TypeScript, served via Nginx
|
||||
- Backend: Node.js 20 with Express 4, TypeScript
|
||||
- Database: PostgreSQL 15 with Prisma ORM
|
||||
- Cache: Redis 7 for session and data caching
|
||||
- Message Queue: RabbitMQ for async processing
|
||||
- Infrastructure: Docker containers, Kubernetes orchestration
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
Client (React) → Nginx → Express API → PostgreSQL
|
||||
↓
|
||||
Redis Cache
|
||||
↓
|
||||
RabbitMQ Queue
|
||||
```
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies for entire monorepo
|
||||
npm install
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with your credentials
|
||||
|
||||
# Start all services with Docker
|
||||
docker-compose up -d
|
||||
|
||||
# Run database migrations
|
||||
npm run db:migrate
|
||||
|
||||
# Seed initial data
|
||||
npm run db:seed
|
||||
|
||||
# Start development servers
|
||||
npm run dev # Starts backend and frontend
|
||||
```
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Test-Driven Development**: Write tests before implementation
|
||||
2. **Type Safety First**: Use TypeScript strict mode throughout
|
||||
3. **Component Composition**: Favor small, reusable components
|
||||
4. **API Design**: RESTful conventions with proper versioning
|
||||
5. **Error Handling**: Comprehensive error handling from the start
|
||||
6. **Performance**: Optimize for scale (caching, CDN, lazy loading)
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Frontend**: React 18, TypeScript 5, Tailwind CSS, React Query
|
||||
- **Backend**: Node.js 20, Express 4, TypeScript, Prisma
|
||||
- **Database**: PostgreSQL 15, Redis 7
|
||||
- **Infrastructure**: Docker, Kubernetes, Nginx, GitHub Actions
|
||||
- **Testing**: Jest, React Testing Library, Supertest, Playwright
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. **Feature Development**:
|
||||
- Create feature branch: `git checkout -b feature/name`
|
||||
- Work in appropriate context (backend/ or frontend/)
|
||||
- Follow context-specific CLAUDE.md guidelines
|
||||
- Write tests first (TDD)
|
||||
- Run local validation: `npm run lint && npm test`
|
||||
|
||||
2. **Code Review**:
|
||||
- Create PR with detailed description
|
||||
- Ensure CI passes (lint, tests, build)
|
||||
- Get minimum 2 approvals
|
||||
- Address review comments
|
||||
|
||||
3. **Deployment**:
|
||||
- Merge to `main` triggers staging deployment
|
||||
- QA validation on staging
|
||||
- Manual promotion to production
|
||||
- Monitor metrics and logs
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev:backend # Start backend server (port 3000)
|
||||
npm run dev:frontend # Start frontend dev server (port 5173)
|
||||
npm run dev # Start both servers
|
||||
npm test # Run all tests (backend + frontend)
|
||||
npm run lint # Lint all code
|
||||
|
||||
# Production
|
||||
npm run build # Build frontend and backend
|
||||
npm run start # Start production servers
|
||||
|
||||
# Database
|
||||
npm run db:migrate # Run migrations
|
||||
npm run db:seed # Seed data
|
||||
npm run db:reset # Reset database (dev only)
|
||||
|
||||
# Docker
|
||||
docker-compose up -d # Start all services
|
||||
docker-compose logs -f # View logs
|
||||
docker-compose down # Stop all services
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit Tests**: All business logic (80%+ coverage)
|
||||
- **Integration Tests**: API endpoints and database operations
|
||||
- **E2E Tests**: Critical user flows with Playwright
|
||||
- **Performance Tests**: Load testing for API endpoints
|
||||
- **Security Tests**: OWASP compliance scans
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Context-Specific Guidelines**: Always check subdirectory CLAUDE.md files for detailed guidance
|
||||
- **Modular Architecture**: Each major component has its own CLAUDE.md file
|
||||
- **Navigation**: Use Quick Navigation section to find relevant guidelines
|
||||
- **Production Ready**: This is a production-grade setup with enterprise patterns
|
||||
|
||||
---
|
||||
|
||||
For detailed guidelines, see context-specific CLAUDE.md files in subdirectories.
|
||||
|
||||
**Project Type**: Full-Stack Application (Production)
|
||||
**Team Size**: Medium (12 developers)
|
||||
**Architecture**: Modular with context-specific CLAUDE.md files
|
||||
**Lines**: ~150 (Modular root template with native format)
|
||||
@@ -0,0 +1,461 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance for Claude Code when working with this Python API project.
|
||||
|
||||
## Overview
|
||||
|
||||
FastAPI-based RESTful API with PostgreSQL database, JWT authentication, and async SQLAlchemy. Small team (6 developers) following TDD practices with 90%+ test coverage requirement.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project-root/
|
||||
├── app/
|
||||
│ ├── api/
|
||||
│ │ ├── v1/
|
||||
│ │ │ ├── endpoints/ # API endpoints
|
||||
│ │ │ │ ├── auth.py
|
||||
│ │ │ │ ├── users.py
|
||||
│ │ │ │ └── products.py
|
||||
│ │ │ ├── dependencies.py # Shared dependencies
|
||||
│ │ │ └── router.py # API router
|
||||
│ │ └── __init__.py
|
||||
│ ├── core/
|
||||
│ │ ├── config.py # App configuration
|
||||
│ │ ├── security.py # Auth utilities
|
||||
│ │ └── database.py # DB connection
|
||||
│ ├── models/
|
||||
│ │ ├── user.py # SQLAlchemy models
|
||||
│ │ └── product.py
|
||||
│ ├── schemas/
|
||||
│ │ ├── user.py # Pydantic schemas
|
||||
│ │ └── product.py
|
||||
│ ├── services/
|
||||
│ │ ├── auth_service.py # Business logic
|
||||
│ │ ├── user_service.py
|
||||
│ │ └── product_service.py
|
||||
│ ├── utils/
|
||||
│ │ ├── logging.py # Logging utilities
|
||||
│ │ └── validators.py
|
||||
│ ├── middleware/
|
||||
│ │ ├── logging.py # Logging middleware
|
||||
│ │ └── rate_limit.py # Rate limiting
|
||||
│ └── main.py # App entry point
|
||||
├── tests/
|
||||
│ ├── unit/ # Unit tests
|
||||
│ ├── integration/ # Integration tests
|
||||
│ ├── conftest.py # Pytest fixtures
|
||||
│ └── test_main.py
|
||||
├── alembic/
|
||||
│ ├── versions/ # Migration files
|
||||
│ └── env.py # Alembic config
|
||||
├── .env.example
|
||||
├── alembic.ini
|
||||
├── pyproject.toml
|
||||
├── requirements.txt
|
||||
├── Dockerfile
|
||||
└── docker-compose.yml
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
- **app/** - Main application package
|
||||
- **api/v1/** - API version 1 endpoints and routing
|
||||
- **endpoints/** - Path operation functions
|
||||
- **dependencies.py** - Dependency injection (DB sessions, auth)
|
||||
- **core/** - Core utilities (config, security, database)
|
||||
- **models/** - SQLAlchemy ORM models
|
||||
- **schemas/** - Pydantic models for request/response validation
|
||||
- **services/** - Business logic layer (separate from HTTP)
|
||||
- **utils/** - Helper functions (logging, validation)
|
||||
- **middleware/** - FastAPI middleware components
|
||||
- **tests/** - Test suite with pytest
|
||||
- **alembic/** - Database migrations
|
||||
|
||||
## Architecture
|
||||
|
||||
**Layer Pattern**: FastAPI → Services → Models → Database
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
HTTP Request → Router → Dependency Injection → Endpoint → Service → Model → Database
|
||||
↓
|
||||
Response (Pydantic schema)
|
||||
```
|
||||
|
||||
**Components**:
|
||||
- **Endpoints**: HTTP layer, request/response handling with Pydantic
|
||||
- **Services**: Business logic, reusable across endpoints
|
||||
- **Models**: Data access layer with async SQLAlchemy 2.0
|
||||
- **Schemas**: Request/response validation with Pydantic
|
||||
- **Dependencies**: Shared dependencies (DB session, current user)
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Create virtual environment
|
||||
python -m venv venv
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with:
|
||||
# - DATABASE_URL (PostgreSQL connection string)
|
||||
# - SECRET_KEY (for JWT token signing)
|
||||
# - ENVIRONMENT (development/staging/production)
|
||||
|
||||
# Start PostgreSQL (using Docker)
|
||||
docker-compose up -d postgres
|
||||
|
||||
# Run database migrations
|
||||
alembic upgrade head
|
||||
|
||||
# Seed database (if needed)
|
||||
python -m app.scripts.seed
|
||||
|
||||
# Start development server
|
||||
uvicorn app.main:app --reload
|
||||
|
||||
# Server runs at http://localhost:8000
|
||||
# API docs at http://localhost:8000/docs (Swagger UI)
|
||||
# Alternative docs at http://localhost:8000/redoc (ReDoc)
|
||||
```
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Type Hints First**: Use type hints for all function signatures (Python 3.10+)
|
||||
2. **Test-Driven Development**: Write tests before implementation
|
||||
3. **API Design**: Follow RESTful conventions and OpenAPI standards
|
||||
4. **Error Handling**: Comprehensive error handling with proper logging
|
||||
5. **Code Quality**: Black formatting, Ruff linting, 90%+ test coverage
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Framework**: FastAPI 0.104+
|
||||
- **Database**: PostgreSQL 15 with async SQLAlchemy 2.0
|
||||
- **Authentication**: JWT with python-jose
|
||||
- **Validation**: Pydantic v2
|
||||
- **Testing**: Pytest, Pytest-asyncio, HTTPX
|
||||
- **Deployment**: Docker, Uvicorn, Gunicorn
|
||||
- **Logging**: Structlog (JSON format)
|
||||
- **Code Quality**: Black, Ruff, MyPy
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Development Process
|
||||
|
||||
1. Create feature branch from `main`: `git checkout -b feature/name`
|
||||
2. Write tests first (TDD with pytest)
|
||||
3. Implement feature with type hints
|
||||
4. Run formatter, linter, and tests locally
|
||||
5. Create pull request with description
|
||||
6. Code review (minimum 1 approval required)
|
||||
7. Merge to main (auto-deploy to staging)
|
||||
|
||||
### Code Style
|
||||
|
||||
- Use Black for formatting (line length: 100)
|
||||
- Use Ruff for linting (replaces flake8, isort, etc.)
|
||||
- Type hints on all functions and methods
|
||||
- Docstrings for all public functions (Google style)
|
||||
- Example:
|
||||
```python
|
||||
def create_user(db: Session, user_in: UserCreate) -> User:
|
||||
"""Create a new user in the database.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
user_in: User creation data
|
||||
|
||||
Returns:
|
||||
Created user object
|
||||
|
||||
Raises:
|
||||
ValueError: If email already exists
|
||||
"""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
## API Design Guidelines
|
||||
|
||||
### FastAPI Path Operations
|
||||
|
||||
- Use FastAPI path operations (`@app.get`, `@app.post`, etc.)
|
||||
- Version APIs: `/api/v1/users`, `/api/v2/users`
|
||||
- Use Pydantic models for request/response validation
|
||||
- Implement proper HTTP status codes:
|
||||
- `200 OK` - Successful GET/PUT/PATCH
|
||||
- `201 Created` - Successful POST
|
||||
- `204 No Content` - Successful DELETE
|
||||
- `400 Bad Request` - Validation error
|
||||
- `401 Unauthorized` - Authentication required
|
||||
- `403 Forbidden` - Insufficient permissions
|
||||
- `404 Not Found` - Resource not found
|
||||
- `422 Unprocessable Entity` - Pydantic validation error
|
||||
- `500 Internal Server Error` - Server error
|
||||
|
||||
### Documentation
|
||||
|
||||
- Document with OpenAPI (auto-generated by FastAPI)
|
||||
- Access Swagger UI at `/docs`
|
||||
- Access ReDoc at `/redoc`
|
||||
- Add descriptions to path operations:
|
||||
```python
|
||||
@router.get("/users/{user_id}", response_model=UserResponse)
|
||||
async def get_user(user_id: int, db: Session = Depends(get_db)):
|
||||
"""Retrieve a single user by ID."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
## Database Guidelines
|
||||
|
||||
### Migrations with Alembic
|
||||
|
||||
- Use Alembic for migrations
|
||||
- **Never edit existing migrations** - create new ones
|
||||
- Auto-generate migrations: `alembic revision --autogenerate -m "description"`
|
||||
- Review generated migrations before applying
|
||||
- Test migrations on copy of production data
|
||||
- Name migrations descriptively: `add_user_email_index`
|
||||
|
||||
### SQLAlchemy 2.0 Async Style
|
||||
|
||||
- Use async SQLAlchemy 2.0 style
|
||||
- Example:
|
||||
```python
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
async def get_user(db: AsyncSession, user_id: int) -> User | None:
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
return result.scalar_one_or_none()
|
||||
```
|
||||
|
||||
### Query Optimization
|
||||
|
||||
- Implement proper indexes for frequently queried columns
|
||||
- Avoid N+1 queries - use `selectinload` or `joinedload`
|
||||
- Use database transactions for multi-step operations
|
||||
- Paginate large result sets (max 100 items per page)
|
||||
|
||||
## Error Handling
|
||||
|
||||
### FastAPI Exception Handlers
|
||||
|
||||
- Use FastAPI exception handlers
|
||||
- Create custom exceptions:
|
||||
```python
|
||||
class UserNotFoundException(HTTPException):
|
||||
def __init__(self, user_id: int):
|
||||
super().__init__(
|
||||
status_code=404,
|
||||
detail=f"User {user_id} not found"
|
||||
)
|
||||
```
|
||||
|
||||
### Error Response Format
|
||||
|
||||
Return consistent error format:
|
||||
|
||||
```python
|
||||
{
|
||||
"detail": {
|
||||
"code": "VALIDATION_ERROR",
|
||||
"message": "User-friendly message",
|
||||
"errors": [
|
||||
{
|
||||
"field": "email",
|
||||
"message": "Invalid email format"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Logging
|
||||
|
||||
- Log errors with structlog (JSON format)
|
||||
- Include context (request ID, user ID, timestamp)
|
||||
- Log levels: ERROR, WARNING, INFO, DEBUG
|
||||
- Never log sensitive data (passwords, tokens)
|
||||
- Never expose stack traces in production
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Pytest Best Practices
|
||||
|
||||
- Use pytest for all tests
|
||||
- Use pytest fixtures for test setup
|
||||
- Mock external dependencies (httpx, boto3, etc.)
|
||||
- Aim for 90%+ code coverage
|
||||
- Test both success and error paths
|
||||
|
||||
### Example Test
|
||||
|
||||
```python
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from app.main import app
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_user(client: AsyncClient):
|
||||
"""Test user creation endpoint."""
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"email": "test@example.com", "name": "Test User"}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["email"] == "test@example.com"
|
||||
assert "id" in data
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_user_duplicate_email(client: AsyncClient):
|
||||
"""Test user creation with duplicate email."""
|
||||
# First creation
|
||||
await client.post("/api/v1/users", json={"email": "test@example.com"})
|
||||
|
||||
# Duplicate should fail
|
||||
response = await client.post("/api/v1/users", json={"email": "test@example.com"})
|
||||
assert response.status_code == 400
|
||||
```
|
||||
|
||||
### Test Categories
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
pytest
|
||||
|
||||
# Run specific test categories
|
||||
pytest tests/unit/ # Unit tests only
|
||||
pytest tests/integration/ # Integration tests only
|
||||
pytest -m slow # Slow tests (marked with @pytest.mark.slow)
|
||||
|
||||
# Run with coverage
|
||||
pytest --cov=app --cov-report=html
|
||||
```
|
||||
|
||||
## Security Practices
|
||||
|
||||
### Input Validation
|
||||
|
||||
- Validate all input with Pydantic models
|
||||
- Use Pydantic validators for complex validation
|
||||
- Sanitize user input to prevent XSS
|
||||
|
||||
### Database Security
|
||||
|
||||
- Use parameterized queries (SQLAlchemy handles this)
|
||||
- Prevents SQL injection
|
||||
- Never concatenate user input into queries
|
||||
|
||||
### Authentication & Authorization
|
||||
|
||||
- Hash passwords with passlib + bcrypt
|
||||
- Use JWT for stateless authentication
|
||||
- Implement refresh token rotation
|
||||
- Use environment variables for secrets
|
||||
- Example:
|
||||
```python
|
||||
from passlib.context import CryptContext
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
hashed_password = pwd_context.hash(plain_password)
|
||||
```
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
- Implement rate limiting with slowapi
|
||||
- Example: 100 requests per 15 minutes per IP
|
||||
- Protect against brute force attacks
|
||||
|
||||
### CORS
|
||||
|
||||
- Enable CORS properly with CORSMiddleware
|
||||
- Whitelist allowed origins in production
|
||||
- Don't use wildcard (`*`) in production
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Async/Await
|
||||
|
||||
- Use async/await for all I/O operations
|
||||
- Use AsyncSession for database operations
|
||||
- Use httpx.AsyncClient for external HTTP calls
|
||||
|
||||
### Caching
|
||||
|
||||
- Implement caching for frequently accessed data
|
||||
- Use Redis for caching (with aioredis)
|
||||
- Cache expensive computations
|
||||
- Set appropriate TTL (time-to-live)
|
||||
|
||||
### Database Connection Pooling
|
||||
|
||||
- Configure SQLAlchemy connection pool
|
||||
- Set appropriate pool size and overflow
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
uvicorn app.main:app --reload # Start dev server with hot reload
|
||||
pytest # Run all tests
|
||||
pytest --cov=app # Run tests with coverage
|
||||
black . # Format code
|
||||
ruff check . # Lint code
|
||||
mypy app/ # Type checking
|
||||
|
||||
# Database
|
||||
alembic upgrade head # Run all pending migrations
|
||||
alembic downgrade -1 # Rollback last migration
|
||||
alembic revision --autogenerate -m "description" # Create migration
|
||||
alembic current # Show current migration
|
||||
alembic history # Show migration history
|
||||
|
||||
# Production
|
||||
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
|
||||
|
||||
# Docker
|
||||
docker-compose up -d # Start all services
|
||||
docker-compose logs -f app # View application logs
|
||||
docker-compose down # Stop all services
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
|
||||
After starting the server, access API documentation at:
|
||||
|
||||
- **Swagger UI**: http://localhost:8000/docs (interactive)
|
||||
- **ReDoc**: http://localhost:8000/redoc (readable)
|
||||
- **OpenAPI JSON**: http://localhost:8000/openapi.json (raw schema)
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Required environment variables (see `.env.example`):
|
||||
|
||||
```bash
|
||||
# Application
|
||||
ENVIRONMENT=development
|
||||
SECRET_KEY=your-secret-key-here
|
||||
DEBUG=True
|
||||
|
||||
# Database
|
||||
DATABASE_URL=postgresql+asyncpg://user:password@localhost/dbname
|
||||
|
||||
# Authentication
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=7
|
||||
|
||||
# CORS
|
||||
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Project Type**: Python API (FastAPI)
|
||||
**Team Size**: Small (6 developers)
|
||||
**Lines**: ~225 (Python API template with native format)
|
||||
Reference in New Issue
Block a user