Add comprehensive MDC files for various technologies and frameworks

Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including:
- AI/ML libraries (PyTorch, TensorFlow, scikit-learn)
- Backend frameworks (Django, FastAPI, Express, Spring Boot)
- Frontend frameworks (React, Vue, Angular)
- Cloud platforms (AWS, Azure, GCP)
- Development tools (Docker, Kubernetes, Terraform)
- State management libraries
- UI component libraries
- Web technologies and APIs

Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
+310
View File
@@ -0,0 +1,310 @@
---
description: This rule provides comprehensive guidance on Bun library coding standards, best practices, and common patterns. It includes performance optimization, security considerations, and testing strategies.
globs: **/*.{js,ts,jsx,tsx,bun}
---
# Bun Library Best Practices
This document outlines the recommended coding standards, best practices, and patterns for developing applications using the Bun library. Following these guidelines ensures maintainability, performance, security, and overall code quality.
## 1. Code Organization and Structure
### 1.1. Directory Structure
A well-defined directory structure is crucial for maintainability. Consider the following structure as a starting point:
project-root/
├── src/ # Source code
│ ├── components/ # Reusable UI components (if applicable)
│ ├── services/ # Business logic and API interactions
│ ├── utils/ # Utility functions
│ ├── types/ # TypeScript type definitions
│ ├── routes/ # API route handlers
│ ├── middleware/ # Middleware functions
│ ├── models/ # Data models
│ ├── config/ # Configuration files
│ ├── index.ts # Entry point for the application
├── tests/ # Unit and integration tests
├── public/ # Static assets (e.g., images, CSS)
├── .env # Environment variables
├── bun.lockb # Lockfile for dependencies
├── package.json # Project metadata and dependencies
├── tsconfig.json # TypeScript configuration
├── README.md # Project documentation
* **src/**: Contains the main source code of the application.
* **components/**: Houses reusable UI components (if building a web application).
* **services/**: Encapsulates business logic and interactions with external APIs.
* **utils/**: Contains utility functions used throughout the application.
* **types/**: Stores TypeScript type definitions.
* **routes/**: Defines API route handlers using Bun's built-in HTTP server.
* **middleware/**: Includes middleware functions for request processing.
* **models/**: Defines data models used in the application.
* **config/**: Contains configuration files for different environments.
* **tests/**: Holds unit and integration tests.
* **public/**: Stores static assets like images and CSS files.
* **.env**: Stores environment variables.
* **bun.lockb**: Lockfile ensuring consistent dependency versions.
* **package.json**: Defines project metadata and dependencies.
* **tsconfig.json**: Configures TypeScript compiler options.
* **README.md**: Provides project documentation and instructions.
### 1.2. File Naming Conventions
* Use descriptive and consistent file names.
* Prefer camelCase for JavaScript/TypeScript files (e.g., `userService.ts`, `apiHelper.js`).
* Use kebab-case for component directories (e.g., `user-profile`).
* For React components, use PascalCase for the filename (e.g., `UserProfile.tsx`).
### 1.3. Module Organization
* Group related functionality into modules.
* Use clear and concise module names.
* Export only the necessary functions and classes from each module.
* Favor explicit imports over global variables.
### 1.4. Component Architecture (if applicable)
* If building a web application, adopt a component-based architecture (e.g., using React, SolidJS).
* Divide the UI into small, reusable components.
* Follow the Single Responsibility Principle (SRP) for each component.
* Use a consistent component structure (e.g., a folder for each component containing the component file, styles, and tests).
### 1.5. Code Splitting Strategies
* Use dynamic imports (`import()`) to split code into smaller chunks.
* Load only the necessary code for each route or component.
* Consider using a library like `esbuild` (Bun's underlying bundler) or `parcel` to automate code splitting.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Singleton**: Use for managing global resources (e.g., database connections, configuration).
* **Factory**: Use for creating objects without specifying their concrete classes.
* **Observer**: Use for implementing event-driven systems.
* **Middleware**: Use to handle requests and responses in a centralized manner.
* **Dependency Injection**: Use to decouple components and improve testability.
### 2.2. Recommended Approaches for Common Tasks
* **API Request Handling**: Utilize `fetch` API provided by Bun for making HTTP requests.
* **File System Operations**: Use `Bun.file()` and other built-in functions for reading and writing files.
* **Process Management**: Leverage `Bun.spawn()` or `Bun.serve()` to manage child processes and servers.
* **Environment Variable Access**: Use `Bun.env` or `process.env` to access environment variables.
* **Logging**: Implement logging using `console.log` or a dedicated logging library like `pino`.
### 2.3. Anti-patterns and Code Smells
* **Global State**: Avoid using global variables for application state. Use state management solutions instead.
* **Long Functions**: Break down long functions into smaller, more manageable functions.
* **Duplicated Code**: Extract common logic into reusable functions or modules.
* **Magic Numbers**: Use named constants instead of hardcoded values.
* **Ignoring Errors**: Always handle errors properly using try-catch blocks or error handling middleware.
### 2.4. State Management Best Practices
* If your application requires complex state management, consider using a library like Zustand, Valtio, or Jotai.
* Choose a state management solution that fits the complexity of your application.
* Keep state updates predictable and consistent.
* Avoid mutating state directly.
### 2.5. Error Handling Patterns
* Use try-catch blocks to handle synchronous errors.
* Use `async/await` with try-catch blocks for asynchronous errors.
* Implement error handling middleware to catch unhandled exceptions.
* Log errors with relevant information (e.g., stack trace, request details).
* Provide informative error messages to the user.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Minimize Dependencies**: Reduce the number of dependencies to decrease bundle size and install time.
* **Code Splitting**: Split code into smaller chunks that can be loaded on demand.
* **Tree Shaking**: Remove unused code during the build process.
* **Caching**: Cache frequently accessed data to reduce latency.
* **Compression**: Compress responses using gzip or Brotli to reduce network traffic.
* **Efficient Algorithms**: Choose the most efficient algorithms for your tasks.
### 3.2. Memory Management
* Avoid memory leaks by properly releasing resources.
* Use weak references to avoid circular dependencies.
* Monitor memory usage using tools like `bun --inspect`.
* Be mindful of large data structures and use streams when appropriate.
### 3.3. Rendering Optimization (if applicable)
* Use virtualization for large lists or tables.
* Optimize images and other assets.
* Use memoization to avoid unnecessary re-renders.
* Profile rendering performance using browser developer tools.
### 3.4. Bundle Size Optimization
* Use a bundler like `esbuild` to minimize bundle size.
* Remove unused code and dependencies.
* Use code splitting to load only the necessary code.
* Consider using a smaller alternative to large libraries.
### 3.5. Lazy Loading Strategies
* Use dynamic imports (`import()`) to load modules on demand.
* Implement lazy loading for images and other assets.
* Use a library like `react-lazyload` (if using React) to simplify lazy loading.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and How to Prevent Them
* **Cross-Site Scripting (XSS)**: Sanitize user input to prevent malicious scripts from being injected into the page.
* **Cross-Site Request Forgery (CSRF)**: Use CSRF tokens to prevent attackers from forging requests on behalf of authenticated users.
* **SQL Injection**: Use parameterized queries or an ORM to prevent attackers from injecting malicious SQL code.
* **Authentication and Authorization**: Implement robust authentication and authorization mechanisms to protect sensitive data.
* **Denial of Service (DoS)**: Implement rate limiting and other measures to prevent attackers from overwhelming the server.
### 4.2. Input Validation
* Validate all user input on both the client and server sides.
* Use a validation library like `zod` or `yup` to define validation schemas.
* Sanitize user input to remove potentially harmful characters.
* Escape user input when displaying it on the page.
### 4.3. Authentication and Authorization Patterns
* Use a secure authentication protocol like OAuth 2.0 or OpenID Connect.
* Store passwords securely using a hashing algorithm like bcrypt or Argon2.
* Implement role-based access control (RBAC) to restrict access to sensitive resources.
* Use JSON Web Tokens (JWT) for authentication and authorization.
### 4.4. Data Protection Strategies
* Encrypt sensitive data at rest and in transit.
* Use HTTPS to encrypt communication between the client and server.
* Store encryption keys securely using a key management system.
* Regularly back up data to prevent data loss.
### 4.5. Secure API Communication
* Use HTTPS for all API communication.
* Implement API authentication using API keys or JWTs.
* Rate limit API requests to prevent abuse.
* Validate API requests and responses.
* Use a firewall to protect the API from unauthorized access.
## 5. Testing Approaches
### 5.1. Unit Testing Strategies
* Write unit tests for individual functions and classes.
* Use a testing framework like Jest or Bun's built-in test runner.
* Aim for high code coverage.
* Use mocks and stubs to isolate units of code.
* Test edge cases and error conditions.
### 5.2. Integration Testing
* Write integration tests to verify the interaction between different modules.
* Test the integration of the application with external APIs.
* Use a testing framework like Jest or Mocha.
* Use a testing database or mock API to isolate the tests.
### 5.3. End-to-End Testing
* Write end-to-end tests to verify the entire application flow.
* Use a testing framework like Playwright or Cypress.
* Run tests in a browser environment.
* Test the application from the user's perspective.
### 5.4. Test Organization
* Create a separate `tests` directory for test files.
* Organize test files in a way that mirrors the source code structure.
* Use descriptive test names.
* Follow a consistent testing style.
### 5.5. Mocking and Stubbing
* Use mocks and stubs to isolate units of code during testing.
* Use a mocking library like `jest.mock()` or `sinon`.
* Mock external dependencies to avoid relying on external services.
* Stub functions to control their behavior during testing.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes Developers Make
* **Not Using Strict Mode**: Always use strict mode (`'use strict'`) to catch common coding errors.
* **Ignoring Error Handling**: Always handle errors properly using try-catch blocks or error handling middleware.
* **Leaking Global Variables**: Avoid creating global variables by using `let` or `const` to declare variables.
* **Not Understanding Asynchronous JavaScript**: Understand how asynchronous JavaScript works to avoid common pitfalls like callback hell.
* **Over-Engineering**: Keep the code simple and avoid unnecessary complexity.
### 6.2. Edge Cases to Be Aware Of
* **Handling Null and Undefined Values**: Check for null and undefined values before using them to avoid errors.
* **Integer Overflow**: Be aware of integer overflow and underflow when performing arithmetic operations.
* **Unicode Support**: Properly handle Unicode characters to avoid encoding issues.
* **Time Zone Handling**: Handle time zones correctly to avoid date and time discrepancies.
### 6.3. Version-Specific Issues
* Be aware of breaking changes in new versions of Bun.
* Test the application with different versions of Bun to ensure compatibility.
* Use a version manager like `bunx` to manage different Bun versions.
### 6.4. Compatibility Concerns
* Ensure the application is compatible with different operating systems and browsers.
* Use polyfills to support older browsers.
* Test the application on different devices to ensure responsiveness.
### 6.5. Debugging Strategies
* Use the `bun --inspect` flag to debug the application using Chrome DevTools.
* Use `console.log` statements to print debugging information.
* Use a debugger like VS Code's built-in debugger.
* Use a logging library to log errors and other important events.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **VS Code**: A popular code editor with excellent TypeScript support.
* **ESLint**: A linter for identifying and fixing code style issues.
* **Prettier**: A code formatter for automatically formatting code.
* **Jest**: A testing framework for unit and integration testing.
* **Playwright/Cypress**: A testing framework for end-to-end testing.
* **Postman/Insomnia**: API client for testing API endpoints.
### 7.2. Build Configuration
* Use a build tool like `esbuild` or `webpack` to bundle the application.
* Configure the build tool to optimize the bundle size and performance.
* Use environment variables to configure the build process for different environments.
### 7.3. Linting and Formatting
* Use ESLint to enforce consistent coding style.
* Use Prettier to automatically format code.
* Integrate ESLint and Prettier into the development workflow using VS Code extensions or command-line tools.
* Configure ESLint and Prettier to follow the project's coding style guidelines.
### 7.4. Deployment Best Practices
* Use a process manager like `pm2` or `systemd` to manage the application in production.
* Deploy the application to a cloud platform like DigitalOcean, Vercel, or Render.
* Use a CI/CD pipeline to automate the deployment process.
* Monitor the application's performance and health using monitoring tools.
### 7.5. CI/CD Integration
* Use a CI/CD platform like GitHub Actions, GitLab CI, or CircleCI to automate the build, test, and deployment process.
* Configure the CI/CD pipeline to run tests, lint code, and build the application on every commit.
* Use environment variables to configure the CI/CD pipeline for different environments.
* Deploy the application to a staging environment before deploying it to production.
By following these best practices, developers can build high-quality, performant, and secure applications using the Bun library. Remember to adapt these guidelines to the specific needs of your project.
@@ -0,0 +1,297 @@
---
description: This rule provides comprehensive guidance on best practices for developing robust, maintainable, and performant Express.js applications, covering aspects from code organization and security to testing and deployment.
globs: **/*.js
---
- # Express.js Best Practices
This document outlines best practices for developing Express.js applications to ensure code quality, maintainability, performance, and security.
## 1. Code Organization and Structure
- ### Directory Structure Best Practices
- **Modular Structure:** Organize your application into logical modules based on functionality (e.g., `controllers`, `models`, `routes`, `middleware`, `services`).
- **Configuration:** Separate configuration files for different environments (development, production, testing).
- **Public Assets:** Keep static assets (CSS, JavaScript, images) in a dedicated `public` directory.
- **Views:** Store template files in a `views` directory. Use a template engine like EJS or Pug.
- **Example Structure:**
my-express-app/
├── controllers/
│ ├── userController.js
│ └── productController.js
├── models/
│ ├── user.js
│ └── product.js
├── routes/
│ ├── userRoutes.js
│ └── productRoutes.js
├── middleware/
│ ├── authMiddleware.js
│ └── errorMiddleware.js
├── services/
│ ├── userService.js
│ └── productService.js
├── config/
│ ├── config.js
│ └── db.js
├── views/
│ ├── index.ejs
│ └── user.ejs
├── public/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── script.js
│ └── images/
├── app.js # Main application file
├── package.json
└── .env # Environment variables
- ### File Naming Conventions
- **Descriptive Names:** Use clear and descriptive names for files and directories.
- **Case Convention:** Use camelCase for JavaScript files and directories. For components consider PascalCase.
- **Route Files:** Name route files according to the resource they handle (e.g., `userRoutes.js`, `productRoutes.js`).
- **Controller Files:** Name controller files according to the resource they handle (e.g., `userController.js`, `productController.js`).
- **Model Files:** Name model files after the data model they represent (e.g., `user.js`, `product.js`).
- ### Module Organization
- **ES Modules:** Use ES modules (`import`/`export`) for modularity.
- **Single Responsibility Principle:** Each module should have a single, well-defined responsibility.
- **Loose Coupling:** Minimize dependencies between modules to improve reusability and testability.
- ### Component Architecture
- **Reusable Components:** Break down the application into reusable components (e.g., UI components, service components).
- **Separation of Concerns:** Separate presentation logic (views) from business logic (controllers/services).
- **Component Composition:** Compose complex components from simpler ones.
- ### Code Splitting Strategies
- **Route-Based Splitting:** Split code based on application routes to reduce initial load time. Use dynamic imports (`import()`) to load modules on demand.
- **Component-Based Splitting:** Split code based on components, loading components only when they are needed.
## 2. Common Patterns and Anti-patterns
- ### Design Patterns Specific to Express
- **Middleware Pattern:** Use middleware functions to handle request processing, authentication, logging, etc.
- **MVC Pattern:** Implement the Model-View-Controller (MVC) pattern to separate concerns and improve code organization.
- **Observer Pattern:** Implement the observer pattern when you need to notify multiple objects about state changes.
- ### Recommended Approaches for Common Tasks
- **Route Handling:** Use Express Router to define routes in separate modules.
- **Error Handling:** Use custom error handling middleware to catch and handle errors gracefully. See section 6 for more details.
- **Data Validation:** Use middleware for validating request data before processing it.
- **Asynchronous Operations:** Use `async/await` or Promises to handle asynchronous operations.
- ### Anti-patterns and Code Smells to Avoid
- **God Object:** Avoid creating a single, massive object that handles too many responsibilities.
- **Callback Hell:** Avoid deeply nested callbacks; use Promises or `async/await` instead.
- **Ignoring Errors:** Always handle errors properly instead of ignoring them.
- **Global Variables:** Minimize the use of global variables to avoid naming conflicts and unexpected behavior.
- **Hardcoding Secrets:** Never hardcode sensitive information (API keys, passwords) in your code. Use environment variables instead.
- ### State Management Best Practices
- **Stateless Controllers:** Keep controllers stateless to improve scalability and testability.
- **Session Management:** Use session management middleware (e.g., `express-session`) to manage user sessions.
- **Caching:** Implement caching strategies (e.g., Redis, Memcached) to improve performance.
- ### Error Handling Patterns
- **Centralized Error Handling:** Create a custom error handling middleware to catch and handle errors from different parts of the application.
- **Error Logging:** Log errors to a file or a monitoring service for debugging and analysis.
- **Custom Error Objects:** Create custom error objects with specific error codes and messages.
- **Graceful Error Messages:** Return user-friendly error messages instead of exposing internal errors.
- **Example Error Handler Middleware:**
javascript
// middleware/errorMiddleware.js
const errorHandler = (err, req, res, next) => {
console.error(err.stack);
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === 'production' ? null : err.stack,
});
};
module.exports = errorHandler;
## 3. Performance Considerations
- ### Optimization Techniques
- **Gzip Compression:** Use Gzip compression to reduce the size of responses.
- **Caching:** Implement caching at different levels (e.g., browser caching, server-side caching) to reduce server load.
- **Connection Pooling:** Use connection pooling for database connections to improve performance.
- **Load Balancing:** Distribute traffic across multiple servers using a load balancer.
- ### Memory Management
- **Avoid Memory Leaks:** Be mindful of memory leaks, especially when working with large datasets or long-running processes. Use tools like `memwatch` to profile.
- **Garbage Collection:** Understand how garbage collection works in Node.js and optimize your code accordingly.
- **Streams:** Use streams for handling large files or data streams to avoid loading the entire data into memory.
- ### Rendering Optimization
- **Template Caching:** Enable template caching in your template engine to improve rendering performance.
- **Minify Assets:** Minify CSS and JavaScript files to reduce their size.
- **Lazy Loading Images:** Lazy load images to improve initial page load time.
- ### Bundle Size Optimization
- **Tree Shaking:** Use tree shaking to remove unused code from your bundles.
- **Code Splitting:** Split your code into smaller chunks to reduce the size of initial bundles.
- **Dependency Analysis:** Analyze your dependencies to identify and remove unnecessary packages.
- ### Lazy Loading Strategies
- **Lazy Load Modules:** Load modules only when they are needed using dynamic imports (`import()`).
- **Lazy Load Images and Other Assets:** Use lazy loading for images and other assets that are not immediately visible on the page.
## 4. Security Best Practices
- ### Common Vulnerabilities and How to Prevent Them
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and encoding output.
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using CSRF tokens.
- **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks.
- **NoSQL Injection:** Sanitize user input and avoid constructing queries from strings to prevent NoSQL injection attacks.
- **Command Injection:** Avoid executing shell commands based on user input. If necessary, sanitize the input and use appropriate escaping.
- **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks.
- **Man-in-the-Middle (MitM):** Use HTTPS to encrypt communication between the client and server and protect against MitM attacks.
- **HTTP Parameter Pollution (HPP):** Avoid using the same parameter multiple times in a request to prevent HPP attacks.
- ### Input Validation
- **Server-Side Validation:** Always validate user input on the server-side, even if you have client-side validation.
- **Data Sanitization:** Sanitize user input to remove potentially harmful characters or code.
- **Schema Validation:** Use schema validation libraries (e.g., Joi, express-validator) to validate request data against a predefined schema.
- ### Authentication and Authorization Patterns
- **Authentication:** Use a secure authentication mechanism (e.g., JWT, OAuth) to verify user identities.
- **Authorization:** Implement role-based access control (RBAC) or attribute-based access control (ABAC) to control access to resources.
- **Secure Password Storage:** Use a strong hashing algorithm (e.g., bcrypt) to store user passwords securely.
- **Multi-Factor Authentication (MFA):** Implement MFA to add an extra layer of security.
- ### Data Protection Strategies
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and other outputs.
- **Access Control:** Restrict access to sensitive data to authorized users and processes.
- ### Secure API Communication
- **HTTPS:** Use HTTPS for all API communication.
- **API Keys:** Use API keys to authenticate clients.
- **Rate Limiting:** Implement rate limiting to prevent abuse and DoS attacks.
- **Input Validation:** Validate all input data to prevent injection attacks.
- **Output Encoding:** Encode all output data to prevent XSS attacks.
## 5. Testing Approaches
- ### Unit Testing Strategies
- **Test-Driven Development (TDD):** Write unit tests before writing the actual code.
- **Test Individual Modules:** Test individual modules in isolation to ensure they work correctly.
- **Mock Dependencies:** Mock external dependencies (e.g., databases, APIs) to isolate the module being tested.
- ### Integration Testing
- **Test Interactions Between Modules:** Test the interactions between different modules to ensure they work together correctly.
- **Test API Endpoints:** Test API endpoints to ensure they return the expected results.
- ### End-to-End Testing
- **Test the Entire Application Flow:** Test the entire application flow from start to finish.
- **Simulate User Interactions:** Simulate user interactions to ensure the application behaves as expected.
- ### Test Organization
- **Separate Test Files:** Create separate test files for each module or component.
- **Descriptive Test Names:** Use clear and descriptive names for test cases.
- **Arrange-Act-Assert Pattern:** Follow the Arrange-Act-Assert pattern in your tests.
- ### Mocking and Stubbing
- **Use Mocking Libraries:** Use mocking libraries (e.g., Jest, Sinon) to create mocks and stubs.
- **Mock External Dependencies:** Mock external dependencies to isolate the module being tested.
- **Stub Function Calls:** Stub function calls to control the behavior of dependencies.
## 6. Common Pitfalls and Gotchas
- ### Frequent Mistakes Developers Make
- **Not Handling Errors Properly:** Always handle errors properly to prevent unexpected behavior.
- **Ignoring Security Vulnerabilities:** Be aware of common security vulnerabilities and take steps to prevent them.
- **Not Using Middleware Wisely:** Use middleware wisely to handle common tasks such as authentication, logging, and error handling.
- **Over-Engineering:** Avoid over-engineering your code by keeping it simple and focused.
- ### Edge Cases to Be Aware Of
- **Handling Large File Uploads:** Use streams or middleware libraries for handling large file uploads to prevent memory issues.
- **Dealing with Timezones:** Be aware of timezone issues when working with dates and times.
- **Handling Unicode Characters:** Properly handle Unicode characters to prevent encoding issues.
- **Dealing with Concurrent Requests:** Implement concurrency control mechanisms to handle concurrent requests safely.
- ### Version-Specific Issues
- **Deprecated Features:** Be aware of deprecated features and use the recommended alternatives.
- **Breaking Changes:** Be aware of breaking changes when upgrading to a new version of Express.js.
- ### Compatibility Concerns
- **Browser Compatibility:** Test your application in different browsers to ensure it works correctly.
- **Operating System Compatibility:** Test your application on different operating systems to ensure it works correctly.
- **Node.js Version Compatibility:** Ensure your application is compatible with the supported versions of Node.js.
- ### Debugging Strategies
- **Use Debugging Tools:** Use debugging tools (e.g., Node.js Inspector, Chrome DevTools) to debug your code.
- **Log Statements:** Use log statements to track the flow of execution and identify issues.
- **Error Messages:** Read error messages carefully to understand the cause of the error.
## 7. Tooling and Environment
- ### Recommended Development Tools
- **IDE:** Use a good IDE such as VS Code, WebStorm, or Sublime Text.
- **Debugger:** Use a debugger to step through your code and identify issues.
- **Linter:** Use a linter (e.g., ESLint) to enforce coding standards.
- **Formatter:** Use a formatter (e.g., Prettier) to format your code automatically.
- ### Build Configuration
- **Use a Build Tool:** Use a build tool (e.g., Webpack, Parcel) to bundle and optimize your code.
- **Configure Build Scripts:** Configure build scripts in your `package.json` file to automate the build process.
- **Use Environment Variables:** Use environment variables to configure your application for different environments.
- ### Linting and Formatting
- **Use ESLint:** Use ESLint to enforce coding standards and identify potential issues.
- **Use Prettier:** Use Prettier to format your code automatically.
- **Configure Editor Integration:** Configure your editor to automatically run ESLint and Prettier on save.
- ### Deployment Best Practices
- **Use a Process Manager:** Use a process manager (e.g., PM2, Forever) to keep your application running in production.
- **Use a Reverse Proxy:** Use a reverse proxy (e.g., Nginx, Apache) to handle incoming requests and forward them to your application.
- **Use a Load Balancer:** Use a load balancer to distribute traffic across multiple servers.
- **Use HTTPS:** Use HTTPS to encrypt communication between the client and server.
- **Monitor Your Application:** Monitor your application to identify and resolve issues.
- ### CI/CD Integration
- **Use a CI/CD Pipeline:** Use a CI/CD pipeline (e.g., Jenkins, Travis CI, CircleCI, GitHub Actions) to automate the build, test, and deployment process.
- **Run Tests Automatically:** Configure your CI/CD pipeline to run tests automatically on every commit.
- **Automate Deployment:** Automate the deployment process to reduce the risk of errors.
@@ -0,0 +1,178 @@
---
description: This rule provides comprehensive guidance on NestJS best practices, coding standards, and architectural patterns. It aims to help developers build scalable, maintainable, and performant NestJS applications by covering code organization, security, testing, and other essential aspects.
globs: **/*.ts
---
- **Code Organization and Structure:**
- **Directory Structure:**
- Adopt a modular structure that reflects the application's domain or features. A common approach includes organizing code into modules, services, controllers, DTOs, and entities, each in their own directory.
- Example:
src/
├── app.module.ts
├── auth/
│ ├── auth.module.ts
│ ├── auth.controller.ts
│ ├── auth.service.ts
│ ├── strategies/
│ │ └── jwt.strategy.ts
│ ├── dtos/
│ │ └── create-user.dto.ts
│ └── entities/
│ └── user.entity.ts
├── users/
│ ├── users.module.ts
│ ├── users.controller.ts
│ ├── users.service.ts
│ └── ...
├── core/
│ ├── filters/
│ │ └── http-exception.filter.ts
│ ├── interceptors/
│ │ └── logging.interceptor.ts
│ └── ...
└── main.ts
- **File Naming Conventions:**
- Use descriptive and consistent naming conventions. Prefix files based on their role (e.g., `user.controller.ts`, `auth.service.ts`, `create-user.dto.ts`).
- Use PascalCase for classes and interfaces (e.g., `UserService`, `CreateUserDto`).
- Use camelCase for instances and variables (e.g., `userService`, `createUserDto`).
- **Module Organization:**
- Encapsulate features within modules. Each module should represent a distinct part of the application and handle related functionality.
- Modules should import necessary dependencies and export components that other modules need.
- Use the `forRoot` and `forFeature` methods for configuration and feature modules, respectively, especially when dealing with database connections or other shared resources.
- **Component Architecture:**
- Follow the SOLID principles for designing components. Each component (controller, service, etc.) should have a single responsibility.
- Use dependency injection to manage dependencies between components, making them more testable and maintainable.
- Controllers should handle request routing and validation, services should implement business logic, and entities should represent data models.
- **Code Splitting Strategies:**
- For large applications, consider splitting modules into smaller, more manageable chunks using feature modules or lazy-loaded modules.
- Use dynamic imports and lazy loading to improve initial load times and reduce bundle size.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:**
- **Dependency Injection:** Use NestJS's built-in dependency injection container to manage dependencies and promote loose coupling.
- **Repository Pattern:** Abstract data access logic into repositories to decouple services from specific database implementations.
- **Unit of Work:** Use a Unit of Work pattern for managing transactions across multiple repositories.
- **CQRS (Command Query Responsibility Segregation):** For complex applications, consider using CQRS to separate read and write operations, improving performance and scalability.
- **Recommended Approaches:**
- Use DTOs (Data Transfer Objects) for data validation and transformation between layers.
- Implement global exception filters to handle errors consistently across the application.
- Use interceptors for logging, caching, and other cross-cutting concerns.
- Utilize pipes for request validation and data transformation.
- Use asynchronous operations (`async/await`) for non-blocking I/O operations.
- **Anti-patterns:**
- **Tight Coupling:** Avoid creating tightly coupled components that are difficult to test and maintain. Use dependency injection and interfaces to promote loose coupling.
- **God Classes:** Avoid creating classes with too many responsibilities. Break down large classes into smaller, more manageable components.
- **Ignoring Errors:** Always handle errors properly using try-catch blocks, exception filters, and logging. Never ignore errors or swallow exceptions.
- **Hardcoding Configuration:** Avoid hardcoding configuration values directly in the code. Use environment variables or configuration files to manage settings.
- **State Management:**
- For simple applications, use services to manage application state.
- For more complex applications, consider using a state management library like Redux or NgRx (although this is less common on the backend).
- Avoid storing sensitive data in the client-side state. Store it securely on the server.
- **Error Handling:**
- Implement a global exception filter to catch unhandled exceptions and return appropriate error responses to the client.
- Use custom exceptions to represent specific error conditions in the application.
- Log errors with sufficient detail to facilitate debugging.
- Return consistent error responses with appropriate HTTP status codes.
- **Performance Considerations:**
- **Optimization Techniques:**
- Use caching to reduce database load and improve response times. NestJS provides built-in support for caching using interceptors.
- Optimize database queries by using indexes, avoiding N+1 queries, and using efficient data retrieval methods.
- Use connection pooling to reduce the overhead of establishing database connections.
- Profile the application to identify performance bottlenecks and optimize accordingly.
- **Memory Management:**
- Avoid memory leaks by properly managing resources and releasing unused objects.
- Use streams for handling large files or data streams.
- Use object pooling to reuse frequently created objects.
- **Rendering Optimization (Server-Side Rendering):**
- Not directly applicable to NestJS, as it's primarily a backend framework. However, if using SSR, optimize rendering performance by caching rendered pages and using efficient templating engines.
- **Bundle Size Optimization:**
- Use tree shaking to remove unused code from the bundle.
- Minify and compress code to reduce bundle size.
- Use code splitting to load only the necessary code for each route or module.
- **Lazy Loading:**
- Use lazy loading to load modules or features on demand, improving initial load times.
- Implement code splitting to create smaller bundles that can be loaded independently.
- **Security Best Practices:**
- **Common Vulnerabilities:**
- **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM that automatically escapes user inputs.
- **Cross-Site Scripting (XSS):** Protect against XSS by sanitizing user inputs and encoding outputs.
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection using tokens or other mechanisms.
- **Authentication and Authorization Flaws:** Secure authentication and authorization by using strong passwords, multi-factor authentication, and role-based access control.
- **Insecure Direct Object References (IDOR):** Prevent IDOR by validating user access to resources before granting access.
- **Input Validation:**
- Validate all user inputs to prevent malicious data from entering the system. Use DTOs and validation pipes to enforce input constraints.
- Sanitize user inputs to remove or escape potentially harmful characters.
- Validate file uploads to prevent malicious files from being uploaded.
- **Authentication and Authorization:**
- Use JWT (JSON Web Tokens) for authentication and authorization.
- Implement role-based access control (RBAC) to restrict access to resources based on user roles.
- Use secure password hashing algorithms (e.g., bcrypt) to store passwords securely.
- Implement rate limiting to prevent brute-force attacks.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS to encrypt communication between the client and server.
- Store secrets securely using environment variables or a secrets management system.
- **Secure API Communication:**
- Use API keys or OAuth 2.0 for API authentication and authorization.
- Implement request validation and rate limiting to protect APIs from abuse.
- Use a secure API gateway to manage API traffic and enforce security policies.
- **Testing Approaches:**
- **Unit Testing:**
- Write unit tests for individual components (services, controllers, etc.) to verify their functionality in isolation.
- Use mocking and stubbing to isolate components from their dependencies.
- Follow the Arrange-Act-Assert pattern for writing clear and concise unit tests.
- **Integration Testing:**
- Write integration tests to verify the interaction between multiple components or modules.
- Test the integration between the application and external systems (e.g., databases, APIs).
- **End-to-End Testing:**
- Write end-to-end tests to verify the application's functionality from a user's perspective.
- Use tools like Puppeteer or Cypress to automate end-to-end tests.
- **Test Organization:**
- Organize tests into separate directories that mirror the application's directory structure.
- Use descriptive names for test files and test cases.
- **Mocking and Stubbing:**
- Use mocking frameworks (e.g., Jest, Sinon.js) to create mock objects and stub methods.
- Use dependency injection to make components easily testable.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes:**
- **Not using DTOs for validation:** Always use DTOs and validation pipes to ensure data integrity.
- **Ignoring environment variables:** Use environment variables for configuration to avoid hardcoding values.
- **Not handling exceptions properly:** Implement global exception filters to catch unhandled exceptions and return appropriate error responses.
- **Overlooking security vulnerabilities:** Be aware of common security vulnerabilities and take steps to mitigate them.
- **Edge Cases:**
- **Handling large file uploads:** Use streams and appropriate buffering techniques to handle large file uploads efficiently.
- **Dealing with concurrent requests:** Use appropriate locking mechanisms or transaction management to handle concurrent requests safely.
- **Version-Specific Issues:**
- Be aware of breaking changes between NestJS versions and update code accordingly.
- Consult the NestJS documentation for migration guides and compatibility information.
- **Compatibility Concerns:**
- Ensure compatibility with different Node.js versions and operating systems.
- Test the application on different browsers and devices to ensure cross-platform compatibility.
- **Debugging Strategies:**
- Use the NestJS debugger to step through code and inspect variables.
- Use logging to track the flow of execution and identify errors.
- Use profiling tools to identify performance bottlenecks.
- **Tooling and Environment:**
- **Recommended Development Tools:**
- **IDE:** Visual Studio Code with NestJS extensions.
- **CLI:** Nest CLI for generating and managing NestJS projects.
- **Database:** PostgreSQL, MySQL, MongoDB, or other compatible database.
- **Testing:** Jest, Supertest.
- **Build Configuration:**
- Use `tsconfig.json` to configure the TypeScript compiler.
- Use Webpack or Parcel to bundle and optimize the application.
- **Linting and Formatting:**
- Use ESLint and Prettier to enforce code style and formatting rules.
- Configure pre-commit hooks to automatically lint and format code before committing.
- **Deployment:**
- Deploy to platforms like Heroku, AWS, Google Cloud, or Azure.
- Use Docker to containerize the application and simplify deployment.
- **CI/CD Integration:**
- Integrate with CI/CD pipelines (e.g., Jenkins, Travis CI, GitHub Actions) to automate testing and deployment.
- Use environment-specific configuration files for different environments (development, staging, production).