Files
gamegroup/CLAUDE.md

217 lines
7.1 KiB
Markdown
Raw Permalink Normal View History

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
GameGroup Backend is a NestJS-based REST API for a game group management platform. It provides team organization, appointment scheduling, asset management, and financial ledgers for gaming groups.
**Tech Stack:** NestJS 10.x, TypeScript 5.x, MySQL 8.0, Redis 7.x, TypeORM
## Common Commands
### Development
```bash
npm run start:dev # Development server with hot reload
npm run start:debug # Debug mode
npm run build # Production build
npm run start:prod # Production server
```
### Database
```bash
# Start MySQL and Redis using Docker
docker compose up -d mysql redis
# Reset database (drops and recreates)
./reset-db.sh
```
### Testing & Quality
```bash
npm run test # Unit tests
npm run test:e2e # End-to-end tests
npm run test:cov # Test coverage
npm run lint # ESLint with auto-fix
npm run format # Prettier formatting
```
## Architecture
### Module Structure
The application follows NestJS's modular architecture:
- **`src/common/`** - Shared utilities and cross-cutting concerns:
- `decorators/` - Custom decorators (`@Public()`, `@Roles()`, `@CurrentUser()`)
- `guards/` - Authentication and authorization guards (JWT, Roles)
- `filters/` - Global exception handling
- `interceptors/` - Response transformation and logging
- `pipes/` - Input validation
- `utils/` - Utility functions (crypto, pagination, date helpers)
- **`src/config/`** - Configuration files loaded by @nestjs/config:
- `app.config.ts` - Application settings
- `database.config.ts` - Database connection
- `jwt.config.ts` - JWT configuration
- `redis.config.ts` - Redis configuration
- `cache.config.ts` - Cache settings
- `performance.config.ts` - CORS and compression settings
- **`src/entities/`** - TypeORM database entities
- **`src/modules/`** - Feature modules (auth, users, groups, games, appointments, ledgers, schedules, blacklist, honors, assets, points, bets)
### Global Middleware Stack
In [src/main.ts](src/main.ts), the following are applied globally:
1. **Compression middleware** - Response compression
2. **CORS** - Configurable origins (dev: all, prod: from env)
3. **Global prefix** - `/api` (configurable via `API_PREFIX`)
4. **Exception filter** - HttpExceptionFilter for unified error responses
5. **Interceptors** - LoggingInterceptor → TransformInterceptor
6. **Validation pipe** - ValidationPipe with class-validator
Swagger documentation is enabled only in development at `/docs`.
### Authentication & Authorization
The system uses a two-layer permission system:
1. **JWT Authentication (JwtAuthGuard)** - Verifies user identity
- Applied globally via APP_GUARD in [src/app.module.ts](src/app.module.ts)
- Use `@Public()` decorator on controllers/methods to bypass authentication
2. **Role-Based Authorization (RolesGuard)** - Checks system-level roles
- Also applied globally via APP_GUARD
- Use `@Roles(UserRole.ADMIN)` to restrict to specific roles
- Currently defined roles: `admin`, `user` (see [src/common/enums/index.ts](src/common/enums/index.ts))
**Important:** Group-level permissions (Owner/Admin/Member) are checked in service layer business logic, not via guards. See [权限管理文档.md](权限管理文档.md) for detailed permission rules.
### Response Format
All responses follow a unified format defined in [src/common/interfaces/response.interface.ts](src/common/interfaces/response.interface.ts):
**Success:**
```json
{
"code": 0,
"message": "success",
"data": { ... },
"timestamp": 1703001234567
}
```
**Error:**
```json
{
"code": 10001,
"message": "用户不存在",
"data": null,
"timestamp": 1703001234567
}
```
Error codes are defined in the `ErrorCode` enum. Use `ErrorCode.CONSTANT_NAME` when throwing errors.
### Common Patterns
**Service with TypeORM:**
```typescript
// Inject repository in constructor
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
) {}
// Use repository methods
async findOne(id: string): Promise<User> {
return this.userRepository.findOne({ where: { id } });
}
```
**Throwing business errors:**
```typescript
import { ErrorCode, ErrorMessage } from '@/common/interfaces/response.interface';
throw new BadRequestException({
code: ErrorCode.USER_NOT_FOUND,
message: ErrorMessage[ErrorCode.USER_NOT_FOUND],
});
```
**Getting current user:**
```typescript
@Get('me')
async getProfile(@CurrentUser() user: User) {
return this.usersService.findOne(user.id);
}
```
**Marking public endpoints:**
```typescript
@Public()
@Post('login')
async login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}
```
### Environment Variables
The app uses `.env` files with fallback order:
1. `.env.${NODE_ENV}` (e.g., `.env.development`, `.env.production`)
2. `.env.local`
3. `.env`
Key environment variables:
- `NODE_ENV` - `development` | `production`
- `PORT` - Server port (default: 3000)
- `API_PREFIX` - API route prefix (default: `api`)
- `DB_HOST`, `DB_PORT`, `DB_USERNAME`, `DB_PASSWORD`, `DB_DATABASE` - MySQL connection
- `REDIS_HOST`, `REDIS_PORT` - Redis connection
- `JWT_SECRET` - JWT signing secret
- `CORS_ORIGIN` - CORS allowed origins (default: `*`)
### TypeORM Configuration
- **Synchronize** - Enabled in development (`synchronize: true`), disable in production
- **Timezone** - Set to `+08:00`
- **Charset** - `utf8mb4`
- **Entities** - Auto-loaded from `**/*.entity{.ts,.js}`
### Creating New Modules
When adding a new feature module:
1. Generate module structure: `nest g resource modules/feature-name`
2. Create entity in `src/entities/`
3. Add module to imports in `src/app.module.ts`
4. Add Swagger tag in `src/main.ts` for documentation
5. Implement service with TypeORM repositories
6. Apply decorators (`@Public()`, `@Roles()`) as needed on controller
### Important Files
- **[src/main.ts](src/main.ts)** - Application bootstrap, middleware configuration
- **[src/app.module.ts](src/app.module.ts)** - Root module, global guards, database setup
- **[src/common/guards/](src/common/guards/)** - JWT and Role guards
- **[src/common/decorators/](src/common/decorators/)** - Custom decorators
- **[src/common/interfaces/response.interface.ts](src/common/interfaces/response.interface.ts)** - Error codes and response format
- **[权限管理文档.md](权限管理文档.md)** - Detailed permission system documentation (Chinese)
### Testing Notes
- Unit tests: `*.spec.ts` files alongside source code
- E2E tests: `test/` directory with Jest configuration at `test/jest-e2e.json`
- Tests use Jest with ts-jest preset
- Coverage reports output to `coverage/` directory
### Deployment Notes
- Docker image builds from `Dockerfile`
- Use `docker-compose.yml` for full stack (MySQL + Redis + App)
- Production uses PM2 for process management (see `ecosystem.config.js`)
- Build output: `dist/` directory