--- # Rules and Memories - Strict Coding Practices ## ๐Ÿง  Memory Bank - Key Concepts to Remember ### Core Principles - **Type Safety First**: Every variable, function, and object must have explicit types - **Functional Programming**: Use map, filter, reduce instead of loops - **Pure Functions**: Functions should not have side effects - **Immutable Data**: Never mutate existing objects, create new ones - **Single Responsibility**: Each function/class should do one thing well - **Explicit Over Implicit**: Always be explicit about types, returns, and behaviors ### Critical Reminders - **NO `any`** - If you need `any`, you need better types - **NO `var`** - Always use `const` or `let` - **NO loops** - Use functional methods instead - **NO console.log** - Use proper logging service - **NO magic numbers** - Use named constants - **NO deep nesting** - Maximum 3 levels of indentation - **NO long functions** - Maximum 50 lines - **NO long files** - Maximum 300 lines ## ๐Ÿ“ Measurement Rules ### File Size Limits - **Maximum file length**: 1000 lines - **Maximum function length**: 50 lines - **Maximum nesting depth**: 3 levels - **Maximum parameters**: 5 per function - **Maximum line length**: 100 characters ### Performance Thresholds - **Function complexity**: Maximum 10 cyclomatic complexity - **Test coverage**: Minimum 80% - **Bundle size**: Monitor and keep reasonable - **Response time**: API endpoints < 200ms - **Database queries**: Maximum 3 per endpoint ## ๐ŸŽฏ Quality Gates - What Blocks Deployment ### Pre-commit Blockers - [ ] ESLint errors (any severity) - [ ] TypeScript compilation errors - [ ] Failing tests (unit/integration) - [ ] Prettier formatting issues - [ ] Unused imports/variables - [ ] Any type usage - [ ] Console.log statements - [ ] Missing return types ### Pre-merge Blockers - [ ] All pre-commit checks pass - [ ] Code review approval (2+ reviewers) - [ ] Security scan clean - [ ] Performance tests pass - [ ] Documentation updated - [ ] Breaking changes documented - [ ] Migration scripts included (if needed) ## ๐Ÿšจ Red Flags - Immediate Action Required ### Code Smells That Must Be Fixed 1. **Any type usage** - Refactor to proper types 2. **Console.log statements** - Replace with Logger service 3. **Try-catch without specific error handling** - Handle specific errors 4. **Functions over 50 lines** - Break into smaller functions 5. **Deep nesting** - Refactor with early returns 6. **Duplicate code** - Extract to shared utilities 7. **Magic numbers/strings** - Create named constants 8. **Missing error handling** - Add proper error boundaries 9. **Synchronous database calls** - Use async/await 10. **Missing input validation** - Add DTOs and validators ### Security Red Flags - Unvalidated user input - SQL injection vulnerabilities - Missing authentication checks - Exposed sensitive data - Weak password policies - Missing CSRF protection - Insecure direct object references ## ๐Ÿ“ Naming Memory Aids ### Variable Naming Patterns ```typescript // Boolean flags const isUserActive = true; const hasPermission = false; const shouldValidate = true; // Collections const userList = []; const activeUsers = []; const userEmails = []; // Functions const getUserById = () => {}; const validateEmail = () => {}; const calculateTotal = () => {}; // Constants const MAX_LOGIN_ATTEMPTS = 3; const API_BASE_URL = 'https://api.example.com'; const DEFAULT_PAGE_SIZE = 10; ``` ### Class Naming Patterns ```typescript // Services class UserService {} class EmailService {} class ValidationService {} // Controllers class UserController {} class AuthController {} class PostController {} // DTOs class CreateUserDto {} class UpdateUserDto {} class UserResponseDto {} // Entities class User {} class Post {} class Comment {} ``` ## ๐Ÿ”„ Common Patterns to Remember ### Error Handling Pattern ```typescript // Always use specific error types try { const result = await someOperation(); return result; } catch (error) { if (error instanceof ValidationError) { throw new BadRequestException(error.message); } if (error instanceof NotFoundError) { throw new NotFoundException(error.message); } throw new InternalServerErrorException('Unexpected error occurred'); } ``` ### Async Function Pattern ```typescript // Always explicit return types for async functions const fetchUserData = async (userId: string): Promise => { const user = await this.userRepository.findById(userId); if (!user) { throw new UserNotFoundException(userId); } return UserData.fromEntity(user); }; ``` ### Validation Pattern ```typescript // Always validate input with DTOs @Post() async createUser(@Body() createUserDto: CreateUserDto): Promise { // DTO validation happens automatically const user = await this.userService.create(createUserDto); return UserResponseDto.fromEntity(user); } ``` ### Repository Pattern ```typescript // Always use interfaces for repositories interface IUserRepository { findById(id: string): Promise; save(user: User): Promise; delete(id: string): Promise; } @Injectable() export class UserRepository implements IUserRepository { // Implementation } ``` ## ๐Ÿงช Testing Patterns to Remember ### Unit Test Structure ```typescript describe('UserService', () => { let service: UserService; let repository: IUserRepository; beforeEach(async () => { // Setup }); describe('methodName', () => { it('should do something when condition', async () => { // Arrange // Act // Assert }); it('should throw error when invalid input', async () => { // Test error cases }); }); }); ``` ### Test Data Patterns ```typescript // Create test data factories const createMockUser = (overrides: Partial = {}): User => ({ id: '1', email: 'test@example.com', name: 'Test User', createdAt: new Date(), ...overrides, }); const createMockCreateUserDto = (overrides: Partial = {}): CreateUserDto => ({ email: 'test@example.com', password: 'password123', name: 'Test User', ...overrides, }); ``` ## ๐Ÿ”ง Development Workflow Memory ### Daily Checklist - [ ] Run `npm run lint:strict` before starting work - [ ] Run `npm run type-check` after major changes - [ ] Write tests for new functionality - [ ] Update documentation if needed - [ ] Check for security implications - [ ] Consider performance impact ### Before Commit Checklist - [ ] All tests pass - [ ] No ESLint errors - [ ] No TypeScript errors - [ ] Code is formatted - [ ] No console.log statements - [ ] No any types - [ ] Proper error handling - [ ] Input validation in place ### Code Review Checklist - [ ] Follows naming conventions - [ ] Proper error handling - [ ] Security considerations - [ ] Performance implications - [ ] Test coverage adequate - [ ] Documentation updated - [ ] No code duplication ## ๐Ÿš€ Performance Memory Aids ### Database Optimization - Use pagination for list endpoints - Implement proper indexing - Use database transactions when needed - Avoid N+1 queries - Use connection pooling ### Caching Strategy ```typescript // Cache frequently accessed data @Cacheable('user', 300) // 5 minutes async findOne(id: string): Promise { return this.userRepository.findById(id); } // Invalidate cache on updates @CacheEvict('user', { allEntries: true }) async update(id: string, data: UpdateUserDto): Promise { // Update logic } ``` ### Memory Management - Dispose of resources properly - Avoid memory leaks - Use streaming for large data - Implement proper cleanup in services ## ๐Ÿ”’ Security Memory Aids ### Authentication Checklist - [ ] JWT tokens properly validated - [ ] Password hashing with bcrypt - [ ] Rate limiting implemented - [ ] CORS properly configured - [ ] Helmet security headers ### Input Validation Checklist - [ ] All inputs validated with DTOs - [ ] SQL injection prevention - [ ] XSS protection - [ ] File upload validation - [ ] Size limits enforced ### Authorization Patterns ```typescript // Use guards and decorators @UseGuards(JwtAuthGuard, RolesGuard) @Roles('admin') @Get('admin-only') async adminEndpoint(): Promise { return 'Admin only content'; } ``` ## ๐Ÿ“Š Monitoring and Alerting ### Key Metrics to Track - Response times - Error rates - Memory usage - Database query performance - API usage patterns - Security events ### Logging Standards ```typescript // Use structured logging this.logger.log(`User ${userId} created successfully`, { userId, timestamp: new Date().toISOString(), action: 'user_created', }); ``` ## ๐Ÿ”„ Refactoring Memory Aids ### When to Refactor - Functions over 50 lines - Deep nesting (>3 levels) - Code duplication - Complex conditionals - Poor naming - Missing error handling ### Refactoring Techniques - Extract method - Extract class - Replace magic numbers with constants - Use early returns - Replace loops with functional methods - Extract interfaces ## ๐ŸŽ“ Learning Resources ### TypeScript Best Practices - Use strict mode always - Prefer interfaces over types for object shapes - Use type guards for runtime type checking - Leverage utility types (Partial, Pick, Omit) - Use generic types for reusable code ### NestJS Best Practices - Use dependency injection - Implement proper error handling - Use guards for authentication/authorization - Use interceptors for cross-cutting concerns - Use pipes for validation and transformation ### Functional Programming - Pure functions (no side effects) - Immutable data structures - Higher-order functions - Function composition - Avoid mutations ## ๐Ÿ†˜ Emergency Procedures ### When Rules Need to Be Bypassed 1. Document the exception in `EXCEPTIONS.md` 2. Get team approval via PR review 3. Add specific ESLint disable comment with justification 4. Set a deadline for proper fix 5. Monitor for abuse ### Emergency Override Commands ```bash # Skip pre-commit hooks (DANGEROUS - use only in emergencies) git commit --no-verify -m "emergency fix: [description]" # Temporarily disable ESLint rule // eslint-disable-next-line @typescript-eslint/no-explicit-any const data: any = externalApiResponse; ``` --- ## ๐Ÿ“š Quick Reference Commands ```bash # Check code quality npm run lint:strict npm run type-check npm test # Fix auto-fixable issues npm run lint:strict:fix npm run format # Run specific checks npm run test:unit npm run test:integration npm run test:e2e npm run test:cov ``` --- **Remember**: These rules exist to create maintainable, scalable, and secure applications. When in doubt, choose the more explicit, type-safe, and functional approach. alwaysApply: true ---