mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
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:
@@ -0,0 +1,148 @@
|
||||
---
|
||||
description: Comprehensive best practices for developing with MongoDB, covering schema design, code organization, performance optimization, security considerations, and testing strategies. This rule provides actionable guidance to help developers build robust and scalable MongoDB applications.
|
||||
globs: **/*.{js,ts,mongodb}
|
||||
---
|
||||
- **Understand Schema Differences Between Relational and Document-based Databases:** Recognize that MongoDB's document-oriented model differs significantly from relational databases. Design schemas that reflect the relationships within the data itself, rather than relying on joins.
|
||||
- **Embed Your Data Instead of Relying on Joins:** Favor embedding related data within a single document to minimize the need for costly join operations. This approach can significantly improve read performance.
|
||||
- **Use Indexes For Frequent Operations:** Create indexes on fields that are frequently queried to optimize performance. Carefully consider the types of queries your application will perform and create indexes accordingly. Compound indexes are beneficial for queries involving multiple fields.
|
||||
- **Properly Size Your Servers:** Ensure that your MongoDB server resources are adequately sized for your workload. Monitor resource utilization and scale as needed to maintain optimal performance. Consider CPU, memory, and disk I/O.
|
||||
- **Use Replication or Sharding:** Implement replication or sharding to enhance scalability and reliability. Replication provides data redundancy and high availability, while sharding distributes data across multiple servers to handle larger datasets and higher traffic volumes.
|
||||
|
||||
### 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- `config/`: Contains configuration files for database connections, authentication, and other settings.
|
||||
- `models/`: Defines data models using Mongoose or other ODM libraries. Each model represents a MongoDB collection.
|
||||
- `routes/`: Handles API endpoints and routes for interacting with the database.
|
||||
- `controllers/`: Implements the logic for handling requests, interacting with models, and returning responses.
|
||||
- `services/`: Contains reusable business logic related to data access and manipulation.
|
||||
- `utils/`: Provides utility functions for common tasks such as validation, formatting, and error handling.
|
||||
- `tests/`: Includes unit, integration, and end-to-end tests.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names that reflect the purpose of the file (e.g., `user.model.js`, `auth.controller.ts`, `product.service.js`).
|
||||
- Follow a consistent naming convention across the project (e.g., camelCase or snake_case).
|
||||
- **Module Organization:**
|
||||
- Organize code into modules based on functionality or domain (e.g., `user` module, `product` module).
|
||||
- Use ES modules or CommonJS modules to encapsulate code and manage dependencies.
|
||||
- **Component Architecture:**
|
||||
- Design reusable components for common tasks such as data validation, error handling, and authentication.
|
||||
- Follow the principles of separation of concerns and single responsibility.
|
||||
- **Code Splitting Strategies:**
|
||||
- Implement lazy loading of modules or components to improve initial load time.
|
||||
- Use code splitting to break down large bundles into smaller chunks.
|
||||
|
||||
### 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to MongoDB:**
|
||||
- **Embedded Document Pattern:** Embed related data within a single document to minimize the need for joins.
|
||||
- **Polymorphic Pattern:** Store different types of documents in the same collection using a common base schema and discriminator fields.
|
||||
- **Bucket Pattern:** Group data into buckets based on time or other criteria for efficient querying and aggregation.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- Use Mongoose or other ODM libraries to simplify data modeling and validation.
|
||||
- Implement pagination for large result sets.
|
||||
- Use aggregation pipelines for complex queries and data transformations.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Over-indexing:** Creating too many indexes can degrade write performance.
|
||||
- **Ignoring Performance:** Neglecting to analyze query performance can lead to slow response times.
|
||||
- **Schema Violations:** Allowing inconsistent data to be stored in collections can cause unexpected errors.
|
||||
- **State Management Best Practices:**
|
||||
- Use a state management library such as Redux or Zustand to manage application state.
|
||||
- Store state in a centralized store to ensure consistency and predictability.
|
||||
- **Error Handling Patterns:**
|
||||
- Implement robust error handling to catch and handle exceptions gracefully.
|
||||
- Use try-catch blocks to handle potential errors.
|
||||
- Log errors for debugging and monitoring.
|
||||
|
||||
### 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- Use indexes to optimize query performance.
|
||||
- Avoid using `$where` operator, as it can be slow.
|
||||
- Use projection to retrieve only the necessary fields.
|
||||
- **Memory Management:**
|
||||
- Monitor memory usage and identify potential memory leaks.
|
||||
- Use connection pooling to reuse database connections.
|
||||
- **Rendering Optimization:** (If applicable for UI-based apps using MongoDB data)
|
||||
- Implement virtualization for large lists.
|
||||
- Use memoization to avoid unnecessary re-renders.
|
||||
- **Bundle Size Optimization:** (If applicable)
|
||||
- Minify and compress JavaScript and CSS files.
|
||||
- Remove unused code.
|
||||
- **Lazy Loading Strategies:** (If applicable)
|
||||
- Lazy load images and other resources.
|
||||
- Use code splitting to load modules on demand.
|
||||
|
||||
### 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **NoSQL Injection:** Sanitize user inputs to prevent injection attacks.
|
||||
- **Authentication Bypass:** Implement strong authentication and authorization mechanisms.
|
||||
- **Data Exposure:** Protect sensitive data by encrypting it and controlling access.
|
||||
- **Input Validation:**
|
||||
- Validate all user inputs to prevent malicious data from being stored in the database.
|
||||
- Use a validation library such as Joi or Yup to define validation schemas.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use a secure authentication protocol such as OAuth 2.0 or JWT.
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive data and functionality.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use data masking to protect personally identifiable information (PII).
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS to encrypt communication between the client and server.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
|
||||
### 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests to verify the functionality of individual modules and components.
|
||||
- Use a testing framework such as Jest or Mocha.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between different modules and components.
|
||||
- Test the integration between the application and the database.
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to verify the functionality of the entire application.
|
||||
- Use a testing framework such as Cypress or Playwright.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on functionality or module.
|
||||
- Use descriptive names for test files and test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate units of code during testing.
|
||||
- Use a mocking library such as Sinon or Jest's built-in mocking.
|
||||
|
||||
### 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Not Understanding MongoDB's Query Language:** Failing to grasp the nuances of MongoDB's query language can lead to inefficient queries.
|
||||
- **Ignoring Indexes:** Neglecting to create indexes on frequently queried fields can significantly impact performance.
|
||||
- **Not Handling Errors Properly:** Failing to handle errors gracefully can lead to unexpected application behavior.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Data Type Mismatches:** Ensure that data types are consistent across the application and the database.
|
||||
- **Concurrency Issues:** Handle concurrency issues carefully to prevent data corruption.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility issues between different versions of MongoDB and related libraries.
|
||||
- Consult the documentation for the specific version you are using.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that the application is compatible with different operating systems and browsers.
|
||||
- Test the application on different devices and screen sizes.
|
||||
- **Debugging Strategies:**
|
||||
- Use logging to track the execution flow and identify potential issues.
|
||||
- Use a debugger to step through the code and inspect variables.
|
||||
|
||||
### 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **MongoDB Compass:** A GUI tool for exploring and managing MongoDB databases.
|
||||
- **MongoDB Shell:** A command-line interface for interacting with MongoDB.
|
||||
- **VS Code Extension for MongoDB:** Provides syntax highlighting, code completion, and other features for MongoDB development.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool such as Webpack or Parcel to bundle and optimize the application.
|
||||
- Configure the build tool to minify and compress JavaScript and CSS files.
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter such as ESLint to enforce coding standards.
|
||||
- Use a formatter such as Prettier to automatically format code.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a containerization technology such as Docker to package the application and its dependencies.
|
||||
- Deploy the application to a cloud platform such as AWS, Azure, or Google Cloud.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate the application with a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
- Use a CI/CD tool such as Jenkins, Travis CI, or CircleCI.
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
description: This rule provides best practices for working with Redis, covering code organization, performance, security, testing, and common pitfalls to ensure efficient and reliable usage. It applies to any language file interacting with Redis.
|
||||
globs: **/*.{py,js,go,java,c,cpp,rb,php,ts,rs,kt,scala}
|
||||
---
|
||||
- **General Best Practices**
|
||||
- Follow official Redis documentation and community best practices.
|
||||
- Use the most recent stable version of the Redis client library for your language.
|
||||
- Regularly update the Redis server and client libraries to benefit from bug fixes, performance improvements, and security patches.
|
||||
|
||||
- **Connection Management**
|
||||
- **Connection Pooling:** Use connection pooling to reduce the overhead of creating new connections for each operation. This significantly improves performance, especially in high-traffic scenarios.
|
||||
- **Connection Timeout:** Configure appropriate connection timeouts to prevent indefinite blocking in case of network issues.
|
||||
- **Retry Logic:** Implement retry logic with exponential backoff for transient connection errors.
|
||||
- **Secure Connections:** When connecting to a remote Redis instance, always use TLS/SSL encryption (redis+ssl://) to protect data in transit, especially when dealing with sensitive information. Ensure proper certificate validation.
|
||||
|
||||
- **Data Modeling and Serialization**
|
||||
- **Key Naming:** Use consistent and meaningful key naming conventions. Consider using namespaces or prefixes to organize keys and avoid collisions.
|
||||
- **Data Serialization:** Choose an efficient serialization format (e.g., JSON, Protocol Buffers, MessagePack) and use it consistently. Consider the trade-offs between human readability, storage space, and serialization/deserialization performance.
|
||||
- **Smaller Values:** Redis works best with smaller values. Break larger data structures into smaller chunks and distribute them across multiple keys. This improves memory utilization and performance.
|
||||
- **Data Types:** Leverage Redis's rich data types (strings, lists, sets, sorted sets, hashes, streams) effectively to optimize data storage and operations. Choose the data type that best suits the use case.
|
||||
|
||||
- **Command Usage**
|
||||
- **Transactions:** Use transactions (`MULTI`, `EXEC`, `DISCARD`, `WATCH`) to ensure atomicity when performing multiple operations. Be aware of the limitations of Redis transactions (no rollback on individual command failure).
|
||||
- **Pipelines:** Use pipelines to batch multiple commands together and reduce network round-trip time. This dramatically improves performance for bulk operations.
|
||||
- **Lua Scripting:** Use Lua scripting for complex operations that require atomicity and server-side processing. This reduces network traffic and improves performance compared to executing multiple individual commands.
|
||||
- **Avoid Blocking Commands:** Avoid using blocking commands like `KEYS`, `FLUSHALL`, `FLUSHDB`, `SORT` without `LIMIT` in production environments. These commands can block the Redis server and degrade performance.
|
||||
- **Use SCAN:** Instead of `KEYS`, use the `SCAN` command for iterating over keys in a non-blocking manner. This allows the Redis server to continue serving other requests while iterating.
|
||||
- **Efficient Deletion:** Instead of `FLUSHALL` or `FLUSHDB`, use `SCAN` with `DEL` to delete keys in batches, minimizing disruption to the server.
|
||||
- **TTL Management:** Set appropriate Time-To-Live (TTL) values for keys to automatically expire data that is no longer needed. This helps manage memory usage and prevent data from becoming stale.
|
||||
|
||||
- **Memory Management**
|
||||
- **Maxmemory:** Configure the `maxmemory` directive to limit the amount of memory Redis can use. When the limit is reached, Redis will evict keys based on the configured eviction policy.
|
||||
- **Eviction Policies:** Choose an appropriate eviction policy (e.g., `LRU`, `LFU`, `volatile-ttl`) based on your application's needs. Understand the trade-offs between different eviction policies.
|
||||
- **Memory Fragmentation:** Monitor memory fragmentation and consider restarting Redis periodically to defragment memory. The `INFO memory` command provides information about memory usage and fragmentation.
|
||||
|
||||
- **Performance Monitoring and Tuning**
|
||||
- **Redis Monitor:** Use the `MONITOR` command (with caution in production) to observe real-time commands being executed on the server. This can help identify performance bottlenecks.
|
||||
- **Redis Slow Log:** Configure the Redis slow log to record commands that take longer than a specified amount of time to execute. Analyze the slow log to identify performance issues.
|
||||
- **INFO Command:** Use the `INFO` command to gather information about the Redis server, including memory usage, CPU usage, and client connections. This information can be used to monitor performance and identify potential problems.
|
||||
- **Latency Monitoring:** Monitor Redis latency using tools like `redis-cli --latency` or dedicated monitoring solutions. High latency can indicate performance issues.
|
||||
|
||||
- **Security Considerations**
|
||||
- **Authentication:** Enable authentication using the `requirepass` directive to protect the Redis server from unauthorized access. Use a strong password.
|
||||
- **Access Control Lists (ACLs):** Use ACLs to restrict access to specific commands and keys for different users. This provides fine-grained control over access to Redis data.
|
||||
- **Network Security:** Restrict network access to the Redis server using firewalls or other network security measures. Only allow connections from trusted sources.
|
||||
- **Disable Unsafe Commands:** Disable or rename potentially dangerous commands like `FLUSHALL`, `FLUSHDB`, `KEYS`, `EVAL` using the `rename-command` directive. This reduces the risk of accidental or malicious misuse.
|
||||
- **Regular Audits:** Conduct regular security audits of the Redis configuration and usage patterns to identify and address potential vulnerabilities.
|
||||
- **Input Validation:** Always validate and sanitize any data being stored in Redis to prevent injection attacks.
|
||||
|
||||
- **Testing Strategies**
|
||||
- **Unit Tests:** Write unit tests to verify the functionality of your code that interacts with Redis. Use mocking or stubbing to isolate the Redis interactions from the rest of the code.
|
||||
- **Integration Tests:** Write integration tests to verify the interaction between your code and the Redis server. Use a dedicated test Redis instance for integration tests.
|
||||
- **End-to-End Tests:** Write end-to-end tests to verify the entire application flow, including the interaction with Redis. This ensures that the application works correctly in a realistic environment.
|
||||
- **Data Population:** When testing, consider populating your redis database with a representative set of data.
|
||||
- **Test Organization:** Organize tests logically, separating unit, integration, and end-to-end tests into different directories or modules.
|
||||
- **Mocking and Stubbing:** Use mocking and stubbing frameworks to simulate Redis behavior during unit tests.
|
||||
|
||||
- **Code Organization and Structure**
|
||||
- **Dedicated Module:** Create a dedicated module or class to encapsulate all Redis-related operations. This promotes code reuse and maintainability.
|
||||
- **Configuration Management:** Store Redis connection parameters (host, port, password) in a configuration file or environment variables. This makes it easy to change the Redis configuration without modifying code.
|
||||
- **Abstraction Layer:** Consider creating an abstraction layer on top of the Redis client library to provide a higher-level API for your application. This can improve code readability and make it easier to switch to a different Redis client library in the future.
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
- **N+1 Problem:** Avoid the N+1 problem when retrieving data from Redis. Instead of making multiple individual requests, use pipelining or Lua scripting to retrieve the data in a single request.
|
||||
- **Race Conditions:** Be aware of potential race conditions when updating data in Redis. Use transactions or Lua scripting to ensure atomicity.
|
||||
- **Large Values:** Avoid storing extremely large values in Redis. This can lead to performance issues and memory exhaustion.
|
||||
- **Key Expiration:** Be careful when using key expiration (TTL). If keys expire unexpectedly, it can lead to data loss or inconsistent application behavior.
|
||||
- **Blocking Operations in Event Loops:** Do not perform blocking Redis operations directly in event loops or GUI threads. Use asynchronous operations instead to avoid blocking the main thread.
|
||||
|
||||
- **Tooling and Environment**
|
||||
- **Redis CLI:** Use the Redis CLI (`redis-cli`) for interacting with the Redis server, executing commands, and monitoring performance.
|
||||
- **Redis Desktop Manager:** Use a Redis desktop manager (e.g., RedisInsight, Medis) for visualizing data, managing keys, and monitoring the Redis server.
|
||||
- **Linting and Formatting:** Configure linters and formatters to enforce consistent code style and best practices in your Redis-related code.
|
||||
- **CI/CD Integration:** Integrate Redis testing and deployment into your CI/CD pipeline to automate the testing and deployment process.
|
||||
- **Monitoring Tools:** Utilize monitoring tools like Prometheus, Grafana, or Datadog to monitor Redis performance and health in production environments.
|
||||
Reference in New Issue
Block a user