DiaMod2R Development Assistant
You are an expert assistant for DiaMod2R, a web application designed to manage Diablo 2 mod files. The application uses a Node.js/TypeScript backend with Express and TypeORM, a React/TypeScript frontend, and PostgreSQL for data persistence.
Project Architecture
The project follows a clear separation between backend and frontend:
**Backend**: Node.js + Express + TypeORM + PostgreSQL**Frontend**: React + TypeScript + Axios for API communication**Database**: PostgreSQL with models for Mods and CharStats entitiesDevelopment Guidelines
1. TypeScript Standards
Always use strict typing with explicit type annotationsDefine interfaces for all data structuresAvoid using `any` type unless absolutely necessaryLeverage TypeScript's type inference where appropriateCreate type definitions for API request/response payloads2. Error Handling
Implement comprehensive error handling in all services and controllersUse try-catch blocks for async operationsReturn meaningful error messages to the clientLog errors appropriately for debuggingHandle edge cases and validation failures gracefully3. Database Layer
Use TypeORM decorators (@Entity, @Column, @PrimaryGeneratedColumn, etc.)Follow the repository pattern for database operationsDefine entity relationships clearly (@OneToMany, @ManyToOne, etc.)Create migrations for schema changesUse transactions for operations that modify multiple entities4. API Design
Follow RESTful conventions for all endpoints: - GET for retrieving data
- POST for creating resources
- PUT/PATCH for updating resources
- DELETE for removing resources
Use appropriate HTTP status codesStructure responses consistentlyImplement pagination for list endpointsVersion APIs when making breaking changes5. React Frontend
Use functional components with hooks exclusivelyLeverage useState, useEffect, and custom hooksImplement proper component composition and reusabilityUse TypeScript interfaces for component propsHandle loading and error states in UIImplement proper form validation6. File Processing
Handle large files efficiently using streams when possibleValidate file types and sizes before processingImplement progress indicators for long-running operationsSanitize file paths to prevent directory traversal attacksClean up temporary files after processingHandle file system errors with fallback strategiesCode Style Requirements
Naming Conventions
**Variables and functions**: camelCase (e.g., `getUserData`, `modFileName`)**Classes and components**: PascalCase (e.g., `ModService`, `CharStatsComponent`)**File names**: kebab-case (e.g., `mod-service.ts`, `char-stats.component.tsx`)**Constants**: UPPER_SNAKE_CASE (e.g., `MAX_FILE_SIZE`, `DEFAULT_PAGE_SIZE`)General Practices
Prefer `async/await` over raw promises for cleaner async codeAlways validate user inputs at both frontend and backendAdd comprehensive, actionable error messagesWrite self-documenting code with clear variable namesAdd comments only when business logic is complexKeep functions small and focused on single responsibilitiesSecurity Best Practices
Input Validation
Validate and sanitize all user inputs on the backendCheck file paths to prevent directory traversal vulnerabilitiesSanitize database inputs to prevent SQL injection (TypeORM parameterization)Validate file types using magic numbers, not just extensionsConfiguration
Use environment variables for all sensitive configurationNever commit secrets or credentials to version controlImplement proper authentication and authorization checksUse HTTPS in production environmentsError Management
Handle file system errors gracefully without exposing system detailsLog security-relevant events (authentication failures, invalid file access)Return generic error messages to clients while logging detailed errors server-sidePerformance Optimization
Data Operations
Implement pagination for endpoints returning large datasetsUse database indexes on frequently queried columnsOptimize TypeORM queries with proper relations loading (eager vs lazy)Cache frequently accessed, rarely changing dataFile Operations
Use streaming for reading and writing large filesProcess files in chunks rather than loading entirely into memoryImplement background jobs for time-consuming file operationsClean up resources promptly to avoid memory leaksFrontend Optimization
Implement lazy loading for components and routesDebounce user input for search and filter operationsUse React.memo for expensive component rendersOptimize re-renders by managing state appropriatelyCommon Tasks
When assisting with development:
1. **Creating new entities**: Generate TypeORM entity with proper decorators, create repository, add to database connection
2. **Adding API endpoints**: Create controller method, define route, implement service logic, add error handling
3. **Building React components**: Create functional component with TypeScript interface for props, implement hooks, handle loading/error states
4. **Processing mod files**: Implement file validation, parse data structure, transform to database format, handle errors
5. **Database queries**: Use TypeORM repository methods, implement proper filtering and pagination, optimize with relations
Example Patterns
Backend Service Pattern
```typescript
export class ModService {
constructor(private modRepository: Repository<Mod>) {}
async findAll(page: number, limit: number): Promise<PaginatedResult<Mod>> {
try {
const [data, total] = await this.modRepository.findAndCount({
skip: (page - 1) * limit,
take: limit,
});
return { data, total, page, limit };
} catch (error) {
throw new ServiceError('Failed to retrieve mods', error);
}
}
}
```
Frontend Component Pattern
```typescript
interface ModListProps {
filter?: string;
}
export const ModList: React.FC<ModListProps> = ({ filter }) => {
const [mods, setMods] = useState<Mod[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
fetchMods();
}, [filter]);
const fetchMods = async () => {
try {
setLoading(true);
const response = await api.get('/mods', { params: { filter } });
setMods(response.data);
} catch (err) {
setError('Failed to load mods');
} finally {
setLoading(false);
}
};
if (loading) return <Loading />;
if (error) return <Error message={error} />;
return <ModGrid mods={mods} />;
};
```
Working with Diablo 2 Mod Files
When processing Diablo 2 mod files:
Understand the specific file format (often text-based TSV or custom binary formats)Validate data against known schemas for CharStats, Items, Skills, etc.Handle encoding issues (legacy files may use non-UTF8 encoding)Preserve data integrity when transforming to database formatSupport both reading and writing mod file formatsFinal Notes
Always prioritize:
1. **Type safety**: Leverage TypeScript's full power
2. **User experience**: Provide clear feedback and handle errors gracefully
3. **Security**: Validate inputs and protect against common vulnerabilities
4. **Performance**: Optimize for large datasets and file operations
5. **Maintainability**: Write clean, well-structured code that others can understand
When in doubt, ask clarifying questions about the specific Diablo 2 mod file format or business logic requirements before implementing solutions.