mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +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,4 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing robust, maintainable, and scalable applications using the Fiber web framework in Go. It covers code organization, performance, security, testing, and common pitfalls.
|
||||
globs: **/*.go
|
||||
---
|
||||
@@ -0,0 +1,406 @@
|
||||
---
|
||||
description: This rule enforces best practices for using the `net/http` ServeMux in Go, promoting clean, maintainable, and efficient code. It covers routing, handler design, and error handling specifics to help developers leverage ServeMux effectively.
|
||||
globs: **/*.go
|
||||
---
|
||||
---
|
||||
# servemux Best Practices and Coding Standards
|
||||
|
||||
This document provides comprehensive guidelines for using the `net/http` ServeMux in Go, promoting best practices, coding standards, and efficient development.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
- **Modular Design:** Organize your code into logical modules, each responsible for a specific set of functionalities.
|
||||
- **Handler Grouping:** Group related handlers within the same directory or package. For instance, all user-related handlers could reside in a `users` package.
|
||||
- **Middleware Directory:** Create a dedicated `middleware` directory for reusable middleware functions.
|
||||
- **Internal vs. External:** Utilize the `internal` directory to encapsulate code that should not be exposed outside your module. This enhances encapsulation and reduces the API surface.
|
||||
|
||||
|
||||
project-root/
|
||||
├── cmd/
|
||||
│ └── my-app/
|
||||
│ └── main.go
|
||||
├── internal/
|
||||
│ ├── handlers/
|
||||
│ │ ├── users.go
|
||||
│ │ └── products.go
|
||||
│ └── middleware/
|
||||
│ ├── auth.go
|
||||
│ └── logging.go
|
||||
├── pkg/
|
||||
│ └── utils/
|
||||
│ └── utils.go
|
||||
└── go.mod
|
||||
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
- **Descriptive Names:** Use clear and descriptive file names that reflect the functionality they contain. For example, `users.go` for user-related handlers, and `auth.go` for authentication middleware.
|
||||
- **Handler Specifics:** If a file contains a specific handler, name it accordingly. For example, `get_user_handler.go` or `create_product_handler.go`.
|
||||
- **Lowercase:** Use lowercase for all file names.
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
- **`go.mod`:** Ensure your project has a `go.mod` file to manage dependencies. Run `go mod init <module_name>` to create one.
|
||||
- **Semantic Versioning:** Follow semantic versioning for your modules. Use tags (e.g., `v1.0.0`) to mark releases.
|
||||
- **Vendor Dependencies:** Consider vendoring dependencies using `go mod vendor` to ensure reproducibility.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
- **Separation of Concerns:** Design your components to have a single responsibility. Separate handler logic from business logic and data access.
|
||||
- **Interfaces:** Use interfaces to define contracts between components, promoting loose coupling and testability. For example:
|
||||
|
||||
go
|
||||
type UserStore interface {
|
||||
GetUser(id int) (*User, error)
|
||||
CreateUser(user *User) error
|
||||
}
|
||||
|
||||
type UserHandler struct {
|
||||
store UserStore
|
||||
}
|
||||
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
- **Package-Based Splitting:** Divide your application into packages based on functionality. Each package should be cohesive and have a clear purpose.
|
||||
- **Feature-Based Splitting:** Organize code based on features. Each feature gets its own directory or package containing all relevant components.
|
||||
- **Layered Architecture:** Implement a layered architecture (e.g., presentation, business logic, data access) and split the code accordingly.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to servemux
|
||||
|
||||
- **Middleware Chaining:** Implement middleware as a chain of functions that decorate the handler. This allows for modular and reusable logic. Example:
|
||||
|
||||
go
|
||||
func LoggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("Request: %s %s", r.Method, r.URL.Path)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Usage:
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/", LoggingMiddleware(http.HandlerFunc(myHandler)))
|
||||
|
||||
|
||||
- **Context-Aware Handlers:** Utilize the `context.Context` to pass request-scoped values to handlers. This facilitates tracing, request cancellation, and data sharing.
|
||||
|
||||
go
|
||||
func MyHandler(w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Context().Value("userID").(int)
|
||||
// ...
|
||||
}
|
||||
|
||||
// Setting context value in middleware:
|
||||
ctx := context.WithValue(r.Context(), "userID", 123)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
|
||||
- **Route Grouping (with custom muxes):** Use separate ServeMux instances for different route groups (e.g., API v1, API v2, admin routes). This improves organization and maintainability.
|
||||
|
||||
go
|
||||
v1Mux := http.NewServeMux()
|
||||
v1Mux.HandleFunc("/users", v1UsersHandler)
|
||||
v1Mux.HandleFunc("/products", v1ProductsHandler)
|
||||
|
||||
v2Mux := http.NewServeMux()
|
||||
v2Mux.HandleFunc("/users", v2UsersHandler)
|
||||
v2Mux.HandleFunc("/products", v2ProductsHandler)
|
||||
|
||||
http.Handle("/api/v1/", v1Mux)
|
||||
http.Handle("/api/v2/", v2Mux)
|
||||
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
- **Creating a New ServeMux:** Always use `http.NewServeMux()` to create a new ServeMux instance. Avoid using the default `http.DefaultServeMux` to prevent global state issues. Example:
|
||||
|
||||
go
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", myHandler)
|
||||
http.ListenAndServe(":8080", mux)
|
||||
|
||||
|
||||
- **Registering Handlers:** Use `mux.HandleFunc()` or `mux.Handle()` to register handlers with the ServeMux.
|
||||
|
||||
go
|
||||
mux.HandleFunc("/users", usersHandler)
|
||||
mux.Handle("/products", productHandler{})
|
||||
|
||||
|
||||
- **Serving Static Files:** Use `http.FileServer()` to serve static files.
|
||||
|
||||
go
|
||||
fs := http.FileServer(http.Dir("./static"))
|
||||
mux.Handle("/static/", http.StripPrefix("/static/", fs))
|
||||
|
||||
|
||||
- **Handling HTTP Methods:** Use `http.MethodGet`, `http.MethodPost`, etc., constants to check the HTTP method. With Go 1.22+, specify methods in the pattern itself for `HandleFunc`.
|
||||
|
||||
go
|
||||
mux.HandleFunc("GET /users/{id}", getUserHandler)
|
||||
mux.HandleFunc("POST /users", createUserHandler)
|
||||
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
- **Global State:** Avoid using global variables or the default `http.DefaultServeMux` for request handling, as it can lead to race conditions and difficult debugging.
|
||||
- **Overlapping Routes:** Be mindful of overlapping routes. Go 1.22+ will panic if conflicting patterns are registered. Ensure that your routes are distinct and do not cause conflicts. Properly consider precedence rules.
|
||||
- **Ignoring Errors:** Always handle errors returned by functions. Log errors and return appropriate HTTP status codes to the client.
|
||||
- **Long Handler Functions:** Keep handler functions short and focused. Delegate complex logic to other functions or services.
|
||||
- **Hardcoding Values:** Avoid hardcoding configuration values. Use environment variables or configuration files.
|
||||
- **Lack of Input Validation:** Always validate user input to prevent security vulnerabilities.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
- **Stateless Handlers:** Design handlers to be stateless whenever possible. If state is required, store it in the request context or an external data store.
|
||||
- **Request-Scoped Values:** Use the `context.Context` to store request-scoped values. Avoid using global variables to store state related to a specific request.
|
||||
- **Sessions:** Use secure session management techniques to maintain user sessions.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
- **Centralized Error Handling:** Implement a centralized error handling middleware to catch and log errors. Return appropriate HTTP status codes and error messages to the client.
|
||||
|
||||
go
|
||||
func ErrorHandlingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("Panic: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
- **Custom Error Types:** Define custom error types to provide more context about the error.
|
||||
|
||||
go
|
||||
type ValidationError struct {
|
||||
Field string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ValidationError) Error() string {
|
||||
return fmt.Sprintf("Validation error: %s - %s", e.Field, e.Message)
|
||||
}
|
||||
|
||||
|
||||
- **Logging Errors:** Log errors with sufficient detail for debugging.
|
||||
- **Returning Appropriate Status Codes:** Return appropriate HTTP status codes based on the error. Use descriptive error messages in the response body.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
- **Connection Pooling:** Use connection pooling for database connections to reduce overhead.
|
||||
- **Caching:** Implement caching for frequently accessed data to reduce database load.
|
||||
- **Gzip Compression:** Enable Gzip compression for responses to reduce bandwidth usage.
|
||||
|
||||
go
|
||||
func GzipMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
gz, err := gzip.NewWriterLevel(w, gzip.BestSpeed)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer gz.Close()
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
next.ServeHTTP(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
|
||||
} else {
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type gzipResponseWriter struct {
|
||||
io.Writer
|
||||
http.ResponseWriter
|
||||
}
|
||||
|
||||
func (w gzipResponseWriter) Write(b []byte) (int, error) {
|
||||
return w.Writer.Write(b)
|
||||
}
|
||||
|
||||
|
||||
- **Keep-Alive Connections:** Enable keep-alive connections to reduce connection establishment overhead.
|
||||
- **Efficient Data Structures:** Use efficient data structures and algorithms for data processing.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
- **Avoid Memory Leaks:** Be aware of potential memory leaks, especially when using goroutines. Ensure that all goroutines are properly terminated.
|
||||
- **Object Pooling:** Consider using object pooling for frequently allocated objects.
|
||||
- **String Conversions:** Minimize unnecessary string conversions, as they can be expensive.
|
||||
- **Defer Statements:** Use `defer` statements carefully. While convenient, they can add overhead if overused in performance-critical sections.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
- **Template Caching:** Cache templates to reduce parsing overhead.
|
||||
- **Efficient Template Rendering:** Use efficient template rendering techniques. Consider using pre-compiled templates.
|
||||
- **Minimize DOM Updates:** Minimize DOM updates in the client-side JavaScript code.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
- **Code Minification:** Minify JavaScript and CSS code to reduce bundle size.
|
||||
- **Tree Shaking:** Use tree shaking to remove unused code from the bundle.
|
||||
- **Image Optimization:** Optimize images to reduce file size.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
- **Lazy Loading Images:** Lazy load images that are not immediately visible.
|
||||
- **Code Splitting:** Split the code into smaller chunks that can be loaded on demand.
|
||||
- **Dynamic Imports:** Use dynamic imports to load modules only when they are needed.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
- **SQL Injection:** Prevent SQL injection by using parameterized queries or ORMs.
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input before rendering it in HTML.
|
||||
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens.
|
||||
- **Authentication Bypass:** Implement robust authentication and authorization mechanisms to prevent authentication bypass.
|
||||
- **Denial-of-Service (DoS):** Implement rate limiting and request validation to prevent DoS attacks.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
- **Validate All Inputs:** Validate all user inputs to ensure that they conform to the expected format and values. Use libraries like `ozzo-validation` for complex validation rules.
|
||||
- **Sanitize Inputs:** Sanitize inputs to remove potentially malicious characters.
|
||||
- **Whitelist Inputs:** Use a whitelist approach to only allow specific characters or patterns.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
- **Authentication Middleware:** Implement authentication middleware to verify user credentials.
|
||||
- **Authorization Middleware:** Implement authorization middleware to check user permissions.
|
||||
- **JWT (JSON Web Tokens):** Use JWT for stateless authentication.
|
||||
- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
|
||||
- **Role-Based Access Control (RBAC):** Implement RBAC to manage user permissions.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
- **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
- **Hashing:** Hash passwords with a strong hashing algorithm like bcrypt.
|
||||
- **Salting:** Use salts to prevent rainbow table attacks.
|
||||
- **Data Masking:** Mask sensitive data in logs and error messages.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
- **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
|
||||
- **TLS (Transport Layer Security):** Use TLS 1.3 or higher for secure communication.
|
||||
- **Certificate Pinning:** Consider using certificate pinning to prevent man-in-the-middle attacks.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent abuse.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
- **Test Individual Units:** Unit test individual functions and methods in isolation.
|
||||
- **Mock Dependencies:** Use mocks to isolate the unit under test from its dependencies. Use libraries like `gomock` or `testify/mock`.
|
||||
- **Test Boundary Conditions:** Test boundary conditions and edge cases.
|
||||
- **Table-Driven Tests:** Use table-driven tests to test multiple scenarios with different inputs and outputs.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
- **Test Interactions Between Components:** Integration test the interactions between different components of the application.
|
||||
- **Test Database Interactions:** Test the interactions with the database.
|
||||
- **Test API Endpoints:** Test the API endpoints.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
- **Test the Entire Application:** End-to-end test the entire application flow.
|
||||
- **Use Automated Testing Tools:** Use automated testing tools like Selenium or Cypress.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
- **Keep Tests Close to Code:** Keep test files in the same directory as the code they test. Use the `_test.go` suffix for test files.
|
||||
- **Separate Test Packages:** Consider creating separate test packages for integration and end-to-end tests.
|
||||
- **Descriptive Test Names:** Use descriptive test names that clearly indicate what is being tested.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
- **Use Interfaces:** Define interfaces for dependencies to facilitate mocking.
|
||||
- **Use Mocking Libraries:** Use mocking libraries like `gomock` or `testify/mock` to generate mocks.
|
||||
- **Create Stub Implementations:** Create stub implementations for dependencies that are difficult to mock.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
- **Forgetting to Handle Errors:** Always check and handle errors returned by functions.
|
||||
- **Ignoring Context Cancellation:** Respect context cancellation signals and terminate long-running operations.
|
||||
- **Not Validating Inputs:** Always validate user inputs to prevent security vulnerabilities.
|
||||
- **Using Global State:** Avoid using global variables for request handling, as it can lead to race conditions.
|
||||
- **Overlapping Routes:** Failing to understand route precedence, especially in Go 1.22+ can lead to unexpected behavior or panics during server initialization. Thoroughly test route registrations.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
- **Trailing Slashes:** Be aware of how trailing slashes affect route matching. In Go 1.22+, use `{$}` to match only the path with the trailing slash.
|
||||
- **Wildcard Matching:** Understand how wildcards match different segments of the path. Use `{pathname...}` to match all remaining segments.
|
||||
- **Method Matching:** Ensure that the correct HTTP method is being used for each route. With Go 1.22+, be aware that `GET` also matches `HEAD` requests.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
- **Go 1.22 Routing Enhancements:** Be aware of the new routing enhancements in Go 1.22, including method matching and wildcard support. Understand the new precedence rules.
|
||||
- **Compatibility Issues:** Check for compatibility issues when upgrading to new versions of Go or third-party libraries.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
- **Backwards Compatibility:** Ensure that changes do not break backwards compatibility. Use feature flags to gradually introduce new features.
|
||||
- **API Versioning:** Use API versioning to manage changes to the API.
|
||||
- **Client Compatibility:** Ensure that client applications are compatible with the API.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
- **Logging:** Use logging to track the execution flow and identify errors.
|
||||
- **Debugging Tools:** Use debugging tools like `delve` to step through the code and inspect variables.
|
||||
- **Profiling:** Use profiling tools to identify performance bottlenecks.
|
||||
- **Tracing:** Use tracing tools to track requests across different services.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
- **GoLand:** A powerful IDE for Go development.
|
||||
- **Visual Studio Code with Go Extension:** A lightweight and versatile code editor with excellent Go support.
|
||||
- **Delve:** A Go debugger.
|
||||
- **Profiling Tools:** `pprof` is the built-in Go profiler.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
- **Makefile:** Use a Makefile to automate common build tasks.
|
||||
- **`go build`:** Use `go build` to compile the application.
|
||||
- **`go test`:** Use `go test` to run tests.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
- **`go fmt`:** Use `go fmt` to format the code according to the Go style guidelines.
|
||||
- **`go vet`:** Use `go vet` to identify potential errors in the code.
|
||||
- **`golangci-lint`:** Use `golangci-lint` for more advanced linting.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
- **Containerization:** Use containers (e.g., Docker) to package the application and its dependencies.
|
||||
- **Orchestration:** Use orchestration tools (e.g., Kubernetes) to manage and scale the application.
|
||||
- **Immutable Infrastructure:** Deploy immutable infrastructure to ensure consistency and reproducibility.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
- **Continuous Integration:** Integrate with a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
- **Automated Testing:** Run automated tests as part of the CI/CD pipeline.
|
||||
- **Automated Deployment:** Automate the deployment process using tools like Jenkins, CircleCI, or GitHub Actions.
|
||||
|
||||
## Additional Best Practices
|
||||
|
||||
- **Meaningful Handler Names:** Use meaningful, concise names for handlers, avoiding repetition of context in function names (as per the Google Style Guide).
|
||||
- **Document Code:** Write clear and concise documentation for all functions, methods, and types.
|
||||
- **Code Reviews:** Conduct regular code reviews to ensure code quality and identify potential issues.
|
||||
- **Stay Updated:** Stay up-to-date with the latest Go best practices and security vulnerabilities.
|
||||
|
||||
By following these best practices and coding standards, you can develop robust, maintainable, and efficient applications using the `net/http` ServeMux in Go.
|
||||
@@ -0,0 +1,339 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices and coding standards for developing robust, maintainable, and performant Spring Boot applications, covering code structure, performance, security, testing, and common pitfalls.
|
||||
globs: **/*.java
|
||||
---
|
||||
# Spring Boot Best Practices and Coding Standards
|
||||
|
||||
This document outlines best practices and coding standards for developing applications with Spring Boot. Following these guidelines will help ensure that your applications are robust, maintainable, performant, and secure.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure
|
||||
|
||||
Adopt a layered architecture to separate concerns and improve maintainability. A recommended directory structure is:
|
||||
|
||||
|
||||
src/
|
||||
├── main/
|
||||
│ ├── java/
|
||||
│ │ └── com/example/app/
|
||||
│ │ ├── Application.java (Main entry point)
|
||||
│ │ ├── config/ (Configuration classes)
|
||||
│ │ ├── controller/ (REST controllers)
|
||||
│ │ ├── service/ (Business logic services)
|
||||
│ │ ├── repository/ (Data access repositories)
|
||||
│ │ ├── model/ (Data transfer objects (DTOs), entities)
|
||||
│ │ ├── exception/ (Custom exceptions)
|
||||
│ │ ├── util/ (Utility classes)
|
||||
│ │ └── security/ (Security-related classes)
|
||||
│ └── resources/
|
||||
│ ├── application.properties/application.yml (Application configuration)
|
||||
│ ├── static/ (Static resources like HTML, CSS, JavaScript)
|
||||
│ └── templates/ (View templates, e.g., Thymeleaf)
|
||||
└── test/
|
||||
├── java/
|
||||
│ └── com/example/app/
|
||||
│ ├── controller/ (Controller tests)
|
||||
│ ├── service/ (Service tests)
|
||||
│ └── repository/ (Repository tests)
|
||||
└── resources/
|
||||
├── application.properties/application.yml (Test-specific configuration)
|
||||
|
||||
|
||||
* **Root Package:** Choose a meaningful root package name (e.g., `com.yourcompany.appname`).
|
||||
* **Modularization:** For larger applications, consider breaking down the application into modules (e.g., using Maven or Gradle modules) based on business domains or features.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* **Classes:** Use PascalCase (e.g., `UserController`, `ProductService`).
|
||||
* **Interfaces:** Use PascalCase, often prefixed with `I` (e.g., `ProductRepository`, `IOrderService`). Consider omitting the `I` prefix if it doesn't add value.
|
||||
* **Methods:** Use camelCase (e.g., `getUserById`, `calculateTotal`).
|
||||
* **Variables:** Use camelCase (e.g., `userName`, `productPrice`).
|
||||
* **Constants:** Use UPPER_SNAKE_CASE (e.g., `MAX_RETRIES`, `DEFAULT_TIMEOUT`).
|
||||
* **Configuration Files:** Use lowercase with hyphens (e.g., `application.properties`, `bootstrap.yml`).
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
For larger projects, break down the application into modules. Each module should represent a distinct business domain or feature.
|
||||
|
||||
* **Maven/Gradle Modules:** Use Maven or Gradle to manage module dependencies and build processes.
|
||||
* **Clear Boundaries:** Define clear interfaces between modules to promote loose coupling.
|
||||
* **Independent Deployments:** Design modules to be independently deployable, if possible.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
* **Controllers:** Handle incoming requests and delegate to services. Keep controllers thin.
|
||||
* **Services:** Implement business logic. Services should be transactional.
|
||||
* **Repositories:** Provide data access abstraction. Use Spring Data JPA or other data access technologies.
|
||||
* **Models:** Represent data structures. Use DTOs for transferring data between layers and entities for persistence.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
* **Feature-Based Splitting:** Group code related to a specific feature into its own package or module.
|
||||
* **Layer-Based Splitting:** Separate code based on layers (e.g., presentation, business logic, data access).
|
||||
* **Horizontal vs. Vertical Slicing:** Consider horizontal slicing (grouping similar functionalities across features) or vertical slicing (grouping all functionalities for a specific feature) based on project needs.
|
||||
|
||||
## 2. Common Patterns and Anti-Patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to Spring Boot
|
||||
|
||||
* **Dependency Injection (DI):** Use constructor injection for required dependencies and setter injection for optional dependencies.
|
||||
* **Inversion of Control (IoC):** Let the Spring container manage the lifecycle and dependencies of your beans.
|
||||
* **Aspect-Oriented Programming (AOP):** Use AOP for cross-cutting concerns like logging, security, and transaction management.
|
||||
* **Repository Pattern:** Use Spring Data repositories for simplified data access.
|
||||
* **Service Layer Pattern:** Decouple controllers from business logic by introducing a service layer.
|
||||
* **Template Method Pattern:** Use `JdbcTemplate` or `RestTemplate` for consistent data access or external API calls.
|
||||
* **Factory Pattern:** Use `@Configuration` classes and `@Bean` methods to define and configure beans.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Configuration:** Use `application.properties` or `application.yml` for externalized configuration. Use `@ConfigurationProperties` to bind configuration properties to a class.
|
||||
* **Logging:** Use SLF4J for logging abstraction and a suitable logging implementation (e.g., Logback or Log4j2).
|
||||
* **Exception Handling:** Use `@ControllerAdvice` to handle exceptions globally. Create custom exception classes for specific error scenarios.
|
||||
* **Validation:** Use JSR-303 Bean Validation for validating request parameters and request bodies. Use `@Validated` annotation with appropriate groups.
|
||||
* **Data Transfer:** Use DTOs to transfer data between layers to avoid exposing internal data structures.
|
||||
* **Asynchronous Operations:** Use `@Async` annotation and `TaskExecutor` to perform asynchronous operations.
|
||||
* **Caching:** Use Spring's caching abstraction with implementations like Ehcache, Caffeine, or Redis.
|
||||
* **Scheduling:** Use `@Scheduled` annotation to schedule tasks.
|
||||
* **Transaction Management:** Use `@Transactional` annotation for managing transactions.
|
||||
|
||||
### 2.3 Anti-Patterns and Code Smells to Avoid
|
||||
|
||||
* **God Class:** A class that does too much. Break it down into smaller, more focused classes.
|
||||
* **Long Method:** A method that is too long and complex. Extract smaller methods.
|
||||
* **Feature Envy:** A method that accesses data from another object more than its own. Move the method to the other object.
|
||||
* **Data Clumps:** Groups of data that frequently appear together. Create a new class to encapsulate the data clump.
|
||||
* **Primitive Obsession:** Using primitive data types instead of creating meaningful domain objects.
|
||||
* **Shotgun Surgery:** Making small changes in many different places. Refactor the code to centralize the changes.
|
||||
* **Spaghetti Code:** Code that is difficult to understand and maintain due to its tangled structure.
|
||||
* **Copy-Paste Programming:** Duplicating code instead of reusing existing code. Create reusable components or methods.
|
||||
* **Field Injection:** Use constructor injection instead for required dependencies.
|
||||
* **Tight Coupling:** Classes that are highly dependent on each other. Decouple the classes using interfaces or abstract classes.
|
||||
* **Ignoring Exceptions:** Catching exceptions but not handling them properly. Log the exception and take appropriate action.
|
||||
* **Over-Engineering:** Making the code too complex for the problem it solves. Keep it simple and only add complexity when needed.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
* **Stateless Services:** Design services to be stateless whenever possible. This improves scalability and testability.
|
||||
* **Session Management:** Use Spring Session to manage user sessions in a distributed environment. Store session data in a persistent store like Redis or a database.
|
||||
* **Caching:** Use caching to store frequently accessed data. Choose a suitable caching strategy (e.g., LRU, FIFO).
|
||||
* **Database:** Use a relational database or a NoSQL database to persist data.
|
||||
* **Distributed Transactions:** Use distributed transaction management techniques like two-phase commit (2PC) or Saga pattern for transactions spanning multiple services.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **Global Exception Handling:** Use `@ControllerAdvice` and `@ExceptionHandler` to handle exceptions globally.
|
||||
* **Custom Exceptions:** Create custom exception classes for specific error scenarios.
|
||||
* **Logging:** Log exceptions with sufficient context information (e.g., request parameters, user ID).
|
||||
* **Error Responses:** Return meaningful error responses with appropriate HTTP status codes and error messages.
|
||||
* **Retry Mechanism:** Implement a retry mechanism for transient errors.
|
||||
* **Circuit Breaker:** Use a circuit breaker pattern to prevent cascading failures.
|
||||
* **Dead Letter Queue:** Use a dead letter queue to handle messages that cannot be processed.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Database Query Optimization:** Use indexes, optimize queries, and avoid N+1 queries.
|
||||
* **Caching:** Use caching to reduce database load and improve response times.
|
||||
* **Connection Pooling:** Use connection pooling to reuse database connections.
|
||||
* **Asynchronous Operations:** Use asynchronous operations to offload long-running tasks from the main thread.
|
||||
* **Load Balancing:** Use load balancing to distribute traffic across multiple instances.
|
||||
* **Gzip Compression:** Use Gzip compression to reduce the size of HTTP responses.
|
||||
* **Code Profiling:** Use profiling tools to identify performance bottlenecks.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Object Pooling:** Use object pooling to reuse objects and reduce object creation overhead.
|
||||
* **Avoid Memory Leaks:** Ensure that objects are properly garbage collected.
|
||||
* **Use Appropriate Data Structures:** Choose data structures that are efficient for the operations you perform.
|
||||
* **Optimize Collections:** Use appropriate collection types (e.g., `ArrayList` vs. `LinkedList`) based on usage patterns.
|
||||
* **Lazy Loading:** Use lazy loading to load data only when it is needed.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
* **Template Caching:** Cache frequently used templates to reduce rendering time.
|
||||
* **Minimize DOM Manipulations:** Minimize DOM manipulations in the view layer.
|
||||
* **Use CDN:** Use a Content Delivery Network (CDN) to serve static resources.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
* **Code Splitting:** Split the code into smaller bundles to reduce the initial load time.
|
||||
* **Tree Shaking:** Remove unused code from the bundles.
|
||||
* **Minification:** Minify the code to reduce the bundle size.
|
||||
* **Compression:** Compress the bundles to reduce the transfer size.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
* **Lazy Initialization:** Initialize objects only when they are first accessed.
|
||||
* **Virtual Proxy:** Use a virtual proxy to delay the loading of an object until it is needed.
|
||||
* **Database Lazy Loading:** Use lazy loading features provided by JPA or other data access technologies.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **SQL Injection:** Use parameterized queries or ORM frameworks to prevent SQL injection attacks.
|
||||
* **Cross-Site Scripting (XSS):** Sanitize user input and use output encoding to prevent XSS attacks.
|
||||
* **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to prevent CSRF attacks.
|
||||
* **Authentication and Authorization:** Implement strong authentication and authorization mechanisms.
|
||||
* **Session Management:** Secure session management to prevent session hijacking.
|
||||
* **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks.
|
||||
* **Insecure Direct Object References (IDOR):** Implement access control checks to prevent unauthorized access to objects.
|
||||
* **Security Misconfiguration:** Properly configure security settings to prevent misconfigurations.
|
||||
* **Using Components with Known Vulnerabilities:** Keep dependencies up-to-date to address known vulnerabilities.
|
||||
* **Insufficient Logging and Monitoring:** Implement sufficient logging and monitoring to detect and respond to security incidents.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Whitelisting:** Validate input against a whitelist of allowed values.
|
||||
* **Regular Expressions:** Use regular expressions to validate input format.
|
||||
* **Data Type Validation:** Validate that input is of the expected data type.
|
||||
* **Length Validation:** Validate that input is within the allowed length limits.
|
||||
* **Encoding Validation:** Validate that input is properly encoded.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
|
||||
* **JWT (JSON Web Token):** Use JWT for stateless authentication.
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
|
||||
* **Attribute-Based Access Control (ABAC):** Implement ABAC for fine-grained access control based on attributes.
|
||||
* **Spring Security:** Leverage Spring Security for authentication and authorization.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
* **Hashing:** Hash passwords and other sensitive data using strong hashing algorithms.
|
||||
* **Salting:** Use salting to protect against rainbow table attacks.
|
||||
* **Data Masking:** Mask sensitive data when it is displayed or used for non-production purposes.
|
||||
* **Tokenization:** Tokenize sensitive data to replace it with non-sensitive tokens.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for secure communication.
|
||||
* **TLS/SSL:** Use TLS/SSL to encrypt data in transit.
|
||||
* **API Keys:** Use API keys to authenticate API clients.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent abuse.
|
||||
* **Input Validation:** Validate all input to prevent injection attacks.
|
||||
* **Output Encoding:** Encode output to prevent XSS attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Test-Driven Development (TDD):** Write tests before writing the code.
|
||||
* **Mocking:** Use mocking frameworks (e.g., Mockito) to isolate the unit under test.
|
||||
* **Assertion Libraries:** Use assertion libraries (e.g., AssertJ) for expressive assertions.
|
||||
* **Code Coverage:** Aim for high code coverage.
|
||||
* **Test Naming:** Use clear and descriptive test names.
|
||||
* **Arrange-Act-Assert:** Structure tests using the Arrange-Act-Assert pattern.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Test Slices:** Use Spring Boot's test slices (e.g., `@WebMvcTest`, `@DataJpaTest`) to test specific parts of the application.
|
||||
* **TestContainers:** Use Testcontainers to run integration tests with real dependencies (e.g., databases, message queues).
|
||||
* **Spring Test:** Use Spring's testing support for integration tests.
|
||||
* **Database Testing:** Use an in-memory database or a test database for database integration tests.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Selenium:** Use Selenium to automate browser-based end-to-end tests.
|
||||
* **REST Assured:** Use REST Assured to test REST APIs.
|
||||
* **Headless Browser:** Use a headless browser for faster end-to-end tests.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Test Packages:** Create separate packages for unit tests, integration tests, and end-to-end tests.
|
||||
* **Test Classes:** Create test classes that correspond to the classes under test.
|
||||
* **Test Suites:** Use test suites to group related tests.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Mockito:** Use Mockito for mocking dependencies.
|
||||
* **Spring MockMvc:** Use Spring MockMvc for testing controllers.
|
||||
* **WireMock:** Use WireMock for stubbing external services.
|
||||
* **Avoid Over-Mocking:** Mock only the dependencies that are necessary to isolate the unit under test.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
* **Not Understanding Spring Boot Concepts:** Jumping into Spring Boot without a solid understanding of Spring and Dependency Injection.
|
||||
* **Overusing `@Autowired`:** Using `@Autowired` for field injection instead of constructor injection.
|
||||
* **Not Using Spring Boot Starters:** Manually adding dependencies instead of using Spring Boot Starters.
|
||||
* **Not Externalizing Configuration:** Hardcoding configuration values instead of using `application.properties` or `application.yml`.
|
||||
* **Not Handling Exceptions Properly:** Ignoring exceptions or not providing meaningful error responses.
|
||||
* **Not Writing Tests:** Neglecting to write unit tests and integration tests.
|
||||
* **Using `System.out.println` for Logging:** Using `System.out.println` instead of a proper logging framework.
|
||||
* **Not Securing the Application:** Failing to implement proper security measures.
|
||||
* **Not Monitoring the Application:** Not setting up proper monitoring and alerting.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
* **Null Values:** Handle null values gracefully.
|
||||
* **Empty Collections:** Handle empty collections properly.
|
||||
* **Large Datasets:** Optimize performance for large datasets.
|
||||
* **Concurrency Issues:** Handle concurrency issues properly.
|
||||
* **Network Errors:** Handle network errors gracefully.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
* **Spring Boot Version Compatibility:** Ensure that dependencies are compatible with the Spring Boot version.
|
||||
* **Java Version Compatibility:** Ensure that the Java version is compatible with the Spring Boot version.
|
||||
* **Third-Party Library Compatibility:** Ensure that third-party libraries are compatible with the Spring Boot version.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
* **Browser Compatibility:** Ensure that the application is compatible with different browsers.
|
||||
* **Operating System Compatibility:** Ensure that the application is compatible with different operating systems.
|
||||
* **Device Compatibility:** Ensure that the application is compatible with different devices.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
* **Logging:** Use logging to trace the execution flow and identify errors.
|
||||
* **Debuggers:** Use debuggers to step through the code and inspect variables.
|
||||
* **Profiling Tools:** Use profiling tools to identify performance bottlenecks.
|
||||
* **Remote Debugging:** Use remote debugging to debug applications running on remote servers.
|
||||
* **Heap Dumps:** Use heap dumps to analyze memory usage.
|
||||
* **Thread Dumps:** Use thread dumps to analyze thread activity.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **IDE:** IntelliJ IDEA, Eclipse, or Visual Studio Code.
|
||||
* **Build Tool:** Maven or Gradle.
|
||||
* **Version Control:** Git.
|
||||
* **Database Client:** DBeaver or SQL Developer.
|
||||
* **API Testing Tool:** Postman or Insomnia.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Maven:** Use `pom.xml` to define dependencies and build configuration.
|
||||
* **Gradle:** Use `build.gradle` to define dependencies and build configuration.
|
||||
* **Spring Boot Maven Plugin:** Use the Spring Boot Maven Plugin for packaging and running the application.
|
||||
* **Spring Boot Gradle Plugin:** Use the Spring Boot Gradle Plugin for packaging and running the application.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **Checkstyle:** Use Checkstyle to enforce coding style guidelines.
|
||||
* **PMD:** Use PMD to find potential code defects.
|
||||
* **FindBugs/SpotBugs:** Use FindBugs/SpotBugs to find potential bugs.
|
||||
* **EditorConfig:** Use EditorConfig to maintain consistent coding styles across different editors.
|
||||
* **IntelliJ IDEA Code Style:** Configure IntelliJ IDEA's code style settings to match the project's coding style.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **Containerization:** Use Docker to containerize the application.
|
||||
* **Orchestration:** Use Kubernetes or Docker Swarm to orchestrate containers.
|
||||
* **Cloud Deployment:** Deploy the application to a cloud platform (e.g., AWS, Azure, Google Cloud).
|
||||
* **Configuration Management:** Use configuration management tools (e.g., Spring Cloud Config) to manage configuration in a distributed environment.
|
||||
* **Monitoring:** Set up monitoring to track application performance and health.
|
||||
* **Logging:** Aggregate logs to a central location for analysis.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Continuous Integration (CI):** Use a CI server (e.g., Jenkins, Travis CI, CircleCI) to automatically build and test the application.
|
||||
* **Continuous Delivery (CD):** Use a CD pipeline to automatically deploy the application to production.
|
||||
* **Automated Testing:** Automate unit tests, integration tests, and end-to-end tests.
|
||||
* **Code Quality Checks:** Integrate code quality checks (e.g., Checkstyle, PMD, FindBugs/SpotBugs) into the CI pipeline.
|
||||
@@ -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).
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
description: This rule outlines comprehensive best practices for Laravel development, covering coding standards, security, performance, and testing to ensure maintainable, efficient, and secure applications. It provides guidelines for code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and tooling.
|
||||
globs: **/*.php
|
||||
---
|
||||
- Adhere to PSR coding standards (PSR-1, PSR-2, PSR-12).
|
||||
- Use meaningful and descriptive variable, function, and class names.
|
||||
- Organize routes effectively, leveraging resource controllers and route groups.
|
||||
- Use Eloquent ORM for database interactions; avoid raw SQL queries where possible (unless necessary for performance).
|
||||
- Implement caching strategies using Laravel's caching system for frequently accessed data.
|
||||
- Maintain a clear and consistent project structure following Laravel's conventions (app, config, database, public, resources, routes, storage).
|
||||
- Ensure code simplicity and readability to enhance maintainability. Follow the single responsibility principle.
|
||||
- Keep Laravel and its packages up-to-date to mitigate security vulnerabilities and leverage new features.
|
||||
|
||||
### 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- Follow Laravel's default directory structure: `app` (core application logic), `config` (configuration files), `database` (migrations and seeds), `public` (static assets), `resources` (views and assets), `routes` (route definitions), `storage` (file storage).
|
||||
- Organize `app` directory using subdirectories like `Models`, `Controllers`, `Services`, `Repositories`, `Exceptions`, `Policies`, `Providers`, and `Http/Middleware`.
|
||||
- Consider using modules for larger applications to encapsulate features.
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use PascalCase for class names (e.g., `UserController`).
|
||||
- Use camelCase for variable and function names (e.g., `$userName`, `getUserName()`).
|
||||
- Use snake_case for database table names and column names (e.g., `users`, `user_id`).
|
||||
- Use kebab-case for route names (e.g., `user.profile`).
|
||||
- Use descriptive names that clearly indicate the purpose of the file or class.
|
||||
|
||||
- **Module Organization:**
|
||||
- For larger applications, use packages or modules to organize code into reusable components.
|
||||
- Implement module-specific service providers, routes, and configurations.
|
||||
- Isolate module dependencies to prevent conflicts.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Use Blade components for reusable UI elements.
|
||||
- Create custom components for complex logic and rendering.
|
||||
- Pass data to components using attributes and slots.
|
||||
- Encapsulate component logic in dedicated classes.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Use lazy loading for non-critical features.
|
||||
- Split large controllers into smaller, more manageable classes.
|
||||
- Extract complex logic into service classes or repositories.
|
||||
|
||||
### 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to Laravel:**
|
||||
- **Repository Pattern:** Abstract data access logic from controllers.
|
||||
- **Service Pattern:** Encapsulate business logic into reusable classes.
|
||||
- **Observer Pattern:** Implement event-driven behavior for model changes.
|
||||
- **Factory Pattern:** Create test data and seed databases.
|
||||
- **Strategy Pattern:** Define a family of algorithms and make them interchangeable.
|
||||
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- Use Eloquent ORM for database interactions, including relationships and aggregations.
|
||||
- Use Laravel's validation system for request data validation.
|
||||
- Use middleware for authentication, authorization, and request modification.
|
||||
- Use queues for background processing and asynchronous tasks.
|
||||
- Use events and listeners for decoupling components.
|
||||
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **God Classes:** Avoid creating large classes with too many responsibilities.
|
||||
- **Spaghetti Code:** Avoid complex and unstructured code that is difficult to understand and maintain.
|
||||
- **Copy-Paste Programming:** Avoid duplicating code; instead, create reusable components or functions.
|
||||
- **Ignoring Exceptions:** Always handle exceptions properly to prevent unexpected behavior.
|
||||
- **Over-Engineering:** Don't overcomplicate solutions with unnecessary complexity.
|
||||
- **Mass Assignment Vulnerability:** Use guarded or fillable attributes to protect against mass assignment vulnerabilities.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- Use sessions for storing user-specific data.
|
||||
- Use cookies for storing client-side data.
|
||||
- Use the cache for storing frequently accessed data.
|
||||
- Use databases for persistent data storage.
|
||||
- Consider using Laravel's broadcasting feature for real-time updates.
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Use try-catch blocks to handle exceptions gracefully.
|
||||
- Use Laravel's exception handler to log and report errors.
|
||||
- Implement custom exception classes for specific error scenarios.
|
||||
- Provide informative error messages to users.
|
||||
|
||||
### 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- Use caching to reduce database queries and improve response times.
|
||||
- Use eager loading to reduce N+1 query problems.
|
||||
- Use queues for background processing.
|
||||
- Optimize database queries with indexes and query optimization techniques.
|
||||
- Minimize the use of loops and conditional statements in performance-critical code.
|
||||
|
||||
- **Memory Management:**
|
||||
- Avoid storing large amounts of data in memory.
|
||||
- Use garbage collection to free up memory.
|
||||
- Use streams for processing large files.
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- Use Blade's caching features to cache rendered views.
|
||||
- Use CSS and JavaScript minification to reduce file sizes.
|
||||
- Use image optimization techniques to reduce image sizes.
|
||||
|
||||
- **Bundle Size Optimization:**
|
||||
- Use Laravel Mix to bundle and minify assets.
|
||||
- Remove unused CSS and JavaScript code.
|
||||
- Use code splitting to load only the necessary code for each page.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- Use lazy loading for images and other non-critical assets.
|
||||
- Use route model binding with eager loading to reduce database queries.
|
||||
|
||||
### 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **SQL Injection:** Use Eloquent ORM and prepared statements to prevent SQL injection attacks.
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input and escape output to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use CSRF protection tokens to prevent CSRF attacks.
|
||||
- **Mass Assignment:** Use guarded or fillable attributes to protect against mass assignment vulnerabilities.
|
||||
- **Authentication and Authorization:** Use Laravel's built-in authentication and authorization features.
|
||||
|
||||
- **Input Validation:**
|
||||
- Use Laravel's validation system to validate all user input.
|
||||
- Sanitize user input to remove potentially harmful characters.
|
||||
- Validate file uploads to prevent malicious files from being uploaded.
|
||||
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use Laravel's built-in authentication system for user authentication.
|
||||
- Use policies to define authorization rules.
|
||||
- Use gates to authorize access to specific resources.
|
||||
- Implement two-factor authentication for enhanced security.
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data using Laravel's encryption features.
|
||||
- Store passwords using bcrypt hashing.
|
||||
- Protect API keys and other sensitive configuration data.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Use API tokens for authentication.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Validate API requests and responses.
|
||||
|
||||
### 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Test individual units of code in isolation.
|
||||
- Use mock objects to isolate dependencies.
|
||||
- Write tests for all critical code paths.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different components of the application.
|
||||
- Test database interactions and external API calls.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application from end to end.
|
||||
- Use browser automation tools to simulate user interactions.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into logical groups.
|
||||
- Use descriptive test names.
|
||||
- Follow the arrange-act-assert pattern.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mock objects to isolate dependencies.
|
||||
- Use stubbing to replace complex dependencies with simpler implementations.
|
||||
|
||||
### 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- Not using dependency injection properly.
|
||||
- Writing complex logic in views.
|
||||
- Not using caching effectively.
|
||||
- Ignoring security vulnerabilities.
|
||||
- Not writing tests.
|
||||
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- Handling large file uploads.
|
||||
- Dealing with concurrent requests.
|
||||
- Handling database connection errors.
|
||||
- Handling time zone conversions.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes between Laravel versions.
|
||||
- Consult the Laravel upgrade guide when upgrading to a new version.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility with different PHP versions and extensions.
|
||||
- Ensure compatibility with different database systems.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use Laravel's debugging tools (e.g., debugbar, telescope).
|
||||
- Use logging to track application behavior.
|
||||
- Use Xdebug for step-by-step debugging.
|
||||
|
||||
### 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- PHPStorm or VS Code with PHP extensions.
|
||||
- Composer for dependency management.
|
||||
- MySQL or PostgreSQL for database management.
|
||||
- Docker for containerization.
|
||||
|
||||
- **Build Configuration:**
|
||||
- Use Laravel Mix to compile assets.
|
||||
- Use environment variables to configure the application.
|
||||
- Use a build script to automate the build process.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use PHP CS Fixer to enforce coding standards.
|
||||
- Use ESLint and Prettier for JavaScript and CSS linting and formatting.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Use a deployment tool like Envoyer or Deployer.
|
||||
- Use zero-downtime deployment strategies.
|
||||
- Use a CDN for static assets.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD pipeline to automate testing and deployment.
|
||||
- Use tools like Jenkins, GitLab CI, or GitHub Actions.
|
||||
@@ -0,0 +1,202 @@
|
||||
---
|
||||
description: Comprehensive guide to Django best practices covering code organization, performance, security, testing, and common pitfalls. This rule ensures adherence to community standards for maintainable and efficient Django applications.
|
||||
globs: **/*.py
|
||||
---
|
||||
# Django Best Practices and Coding Standards
|
||||
|
||||
This guide outlines best practices for developing Django applications to ensure code quality, maintainability, performance, and security.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:**
|
||||
- **Project Root:** Manage.py, settings, urls, wsgi.
|
||||
- **Apps:** Each app should reside in its own directory.
|
||||
- **Static Files:** Separate directory for static files (CSS, JavaScript, images).
|
||||
- **Templates:** Dedicated directory for HTML templates.
|
||||
- **Media:** For user-uploaded files.
|
||||
- **Tests:** Tests for each app in a separate tests/ directory.
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use lowercase letters with underscores (snake_case) for Python files and variables (e.g., `models.py`, `user_profile`).
|
||||
- Classes should use CamelCase (e.g., `UserProfile`).
|
||||
- Function names should use snake_case (e.g., `get_user_profile`).
|
||||
|
||||
- **Module Organization:**
|
||||
- Each app should be a self-contained module.
|
||||
- Group related functionalities into submodules within the app.
|
||||
- Use `__init__.py` files to define packages.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Follow the Model-View-Template (MVT) architecture.
|
||||
- Keep models lean and focused on data representation.
|
||||
- Use views for request handling and business logic.
|
||||
- Templates should focus on presentation.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Break down large views into smaller, reusable functions or class-based views.
|
||||
- Use mixins to share functionality across multiple views.
|
||||
- Implement custom template tags and filters for reusable template logic.
|
||||
- Consider using Celery for asynchronous task processing.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Model-View-Template (MVT):** Django's core architectural pattern.
|
||||
- **Form Objects:** Use Django's forms for handling user input and validation.
|
||||
- **Signals:** Implement signals for decoupled event handling.
|
||||
- **Managers:** Use custom model managers to encapsulate query logic.
|
||||
- **DRY (Don't Repeat Yourself):** Avoid redundant code by extracting reusable components.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- **Database Interactions:** Use Django's ORM for database interactions. Avoid raw SQL queries unless necessary.
|
||||
- **Form Handling:** Leverage Django's form classes for data validation and rendering forms.
|
||||
- **URL Routing:** Use named URL patterns for reverse URL lookup.
|
||||
- **Template Inheritance:** Utilize template inheritance to create a consistent look and feel.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Fat Models:** Avoid putting too much business logic in models. Use services or utility functions instead.
|
||||
- **Complex Templates:** Keep templates simple and focused on presentation. Move complex logic to views or custom template tags.
|
||||
- **Hardcoded Values:** Avoid hardcoding values in code. Use settings or environment variables.
|
||||
- **Ignoring Security:** Neglecting security best practices can lead to vulnerabilities.
|
||||
|
||||
- **State Management:**
|
||||
- Use Django's session framework for managing user sessions.
|
||||
- Avoid storing sensitive data in sessions.
|
||||
- Consider using a dedicated caching system (e.g., Redis, Memcached) for storing frequently accessed data.
|
||||
|
||||
- **Error Handling:**
|
||||
- Implement proper error handling using `try...except` blocks.
|
||||
- Use Django's logging framework to log errors and warnings.
|
||||
- Display user-friendly error messages.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Database Optimization:** Use indexes on frequently queried fields.
|
||||
- **Caching:** Implement caching at various levels (e.g., template caching, view caching, database caching).
|
||||
- **Query Optimization:** Use `select_related` and `prefetch_related` to reduce the number of database queries.
|
||||
- **Gzip Compression:** Enable Gzip compression for static files and responses.
|
||||
|
||||
- **Memory Management:**
|
||||
- Avoid loading large datasets into memory. Use iterators or generators.
|
||||
- Close database connections and file handles properly.
|
||||
- Be mindful of memory leaks.
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- Minimize the use of complex template logic.
|
||||
- Use template caching to cache rendered templates.
|
||||
- Optimize images and other static assets.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- Implement lazy loading for images and other resources that are not immediately visible.
|
||||
- Use pagination to display large datasets in smaller chunks.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates and using Django's `escape` filter.
|
||||
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using Django's CSRF protection.
|
||||
- **SQL Injection:** Use Django's ORM to prevent SQL injection attacks. Avoid raw SQL queries.
|
||||
- **Authentication and Authorization Issues:** Implement proper authentication and authorization mechanisms.
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate all user input on both the client-side and server-side.
|
||||
- Use Django's form validation to validate data.
|
||||
- Sanitize user input to remove potentially harmful characters.
|
||||
|
||||
- **Authentication and Authorization:**
|
||||
- Use Django's built-in authentication system for user authentication.
|
||||
- Implement proper authorization checks to restrict access to sensitive resources.
|
||||
- Use Django's permission system to manage user permissions.
|
||||
|
||||
- **Data Protection:**
|
||||
- Store sensitive data securely using encryption.
|
||||
- Use HTTPS to encrypt communication between the client and server.
|
||||
- Protect against data breaches by implementing proper access controls and monitoring.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use authentication tokens or API keys to authenticate API requests.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Validate all API input.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing:**
|
||||
- Write unit tests for individual functions and classes.
|
||||
- Use Django's testing framework to write and run tests.
|
||||
- Mock external dependencies to isolate units of code.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to test the interaction between different components.
|
||||
- Test database interactions, form handling, and view rendering.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to test the entire application flow.
|
||||
- Use tools like Selenium or Cypress to automate browser testing.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate test suites for each app or component.
|
||||
- Use meaningful test names to describe what each test does.
|
||||
- Keep tests concise and focused.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate units of code during testing.
|
||||
- Avoid mocking external dependencies unless necessary.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- **Incorrect Database Configuration:** Ensure that the database settings are configured correctly.
|
||||
- **Improper Static File Handling:** Configure static file serving properly in production.
|
||||
- **Not Using Django's Built-in Features:** Leverage Django's built-in features instead of reinventing the wheel.
|
||||
- **Ignoring Security Warnings:** Address any security warnings or vulnerabilities reported by Django's security checks.
|
||||
|
||||
- **Edge Cases:**
|
||||
- **Handling Time Zones:** Be mindful of time zones and use Django's time zone support.
|
||||
- **Dealing with Unicode:** Handle Unicode characters correctly.
|
||||
- **Managing File Uploads:** Implement proper file upload handling to prevent security vulnerabilities.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility issues between different Django versions.
|
||||
- Consult the Django release notes for information about breaking changes.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your code is compatible with different browsers and devices.
|
||||
- Test your application on different platforms.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use Django's debugging tools to identify and fix errors.
|
||||
- Use logging to track the execution flow of your application.
|
||||
- Consult the Django documentation and community forums for help.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **IDE:** PyCharm, VS Code, Sublime Text
|
||||
- **Package Manager:** pip, uv
|
||||
- **Database Client:** pgAdmin, MySQL Workbench
|
||||
|
||||
- **Build Configuration:**
|
||||
- Use a `requirements.txt` file to manage dependencies.
|
||||
- Use a virtual environment to isolate project dependencies.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use Black to format code automatically.
|
||||
- Use flake8 to lint code and identify potential errors.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Use a production-ready web server (e.g., Gunicorn, uWSGI).
|
||||
- Configure a reverse proxy (e.g., Nginx, Apache).
|
||||
- Use a database server (e.g., PostgreSQL, MySQL).
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your project with a CI/CD pipeline to automate testing and deployment.
|
||||
- Use tools like Jenkins, Travis CI, or GitLab CI.
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- Always follow PEP 8 guidelines for Python code.
|
||||
- Write clear and concise comments.
|
||||
- Keep your code DRY (Don't Repeat Yourself).
|
||||
- Regularly update your dependencies.
|
||||
- Monitor your application for performance and security issues.
|
||||
@@ -0,0 +1,336 @@
|
||||
---
|
||||
description: Comprehensive guidelines for developing robust, scalable, and maintainable FastAPI applications. Covers code structure, performance, security, testing, and common pitfalls.
|
||||
globs: **/*.py
|
||||
---
|
||||
# FastAPI Best Practices: A Comprehensive Guide
|
||||
|
||||
This document provides a comprehensive set of best practices and coding standards for developing FastAPI applications. These guidelines cover various aspects of development, including project structure, common patterns, performance considerations, security, testing, and tooling.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
A well-structured codebase is crucial for maintainability, scalability, and collaboration. Adopting a consistent and predictable project structure makes it easier for developers to navigate and understand the application.
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
Inspired by projects like Netflix's Dispatch, a feature-based directory structure is recommended, especially for larger applications:
|
||||
|
||||
|
||||
fastapi-project/
|
||||
├── alembic/ # Database migrations
|
||||
├── src/ # Source code
|
||||
│ ├── auth/ # Authentication module
|
||||
│ │ ├── router.py # API endpoints for authentication
|
||||
│ │ ├── schemas.py # Pydantic models for request/response
|
||||
│ │ ├── models.py # Database models
|
||||
│ │ ├── dependencies.py# Dependency injection definitions
|
||||
│ │ ├── config.py # Local configurations
|
||||
│ │ ├── constants.py # Constants and error codes
|
||||
│ │ ├── exceptions.py # Custom exceptions
|
||||
│ │ ├── service.py # Business logic
|
||||
│ │ └── utils.py # Utility functions
|
||||
│ ├── aws/ # AWS integration module (example)
|
||||
│ │ ├── ...
|
||||
│ ├── posts/ # Posts module
|
||||
│ │ ├── ...
|
||||
│ ├── config.py # Global configurations
|
||||
│ ├── models.py # Global models
|
||||
│ ├── exceptions.py # Global exceptions
|
||||
│ ├── pagination.py # Pagination logic
|
||||
│ ├── database.py # Database connection and ORM setup
|
||||
│ └── main.py # Main application entry point
|
||||
├── tests/ # Tests
|
||||
│ ├── auth/
|
||||
│ ├── aws/
|
||||
│ └── posts/
|
||||
├── templates/ # Jinja2 Templates
|
||||
│ └── index.html
|
||||
├── requirements/
|
||||
│ ├── base.txt # Base dependencies
|
||||
│ ├── dev.txt # Development dependencies
|
||||
│ └── prod.txt # Production dependencies
|
||||
├── .env # Environment variables
|
||||
├── .gitignore # Git ignore file
|
||||
├── logging.ini # Logging configuration
|
||||
└── alembic.ini # Alembic configuration
|
||||
|
||||
|
||||
Key aspects of this structure:
|
||||
|
||||
* `src/`: The root directory containing all application code.
|
||||
* Module-based organization: Features are grouped into modules (e.g., `auth`, `posts`). Each module contains its own set of `router.py`, `schemas.py`, `models.py`, etc. This promotes loose coupling and high cohesion.
|
||||
* `main.py`: The entry point of the FastAPI application.
|
||||
* `config.py`: Stores global configurations.
|
||||
* `database.py`: Handles database connection and ORM setup (e.g., SQLAlchemy).
|
||||
* `requirements/`: Separate dependency files for different environments.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* Python files: Use lowercase with underscores (e.g., `user_service.py`).
|
||||
* Pydantic schemas: Use PascalCase with the suffix "Schema" or "Model" (e.g., `UserSchema`, `PostModel`).
|
||||
* Database models: Use PascalCase (e.g., `User`, `Post`).
|
||||
* Routers: Typically named `router.py` within each module.
|
||||
* Configuration files: `config.py`
|
||||
* Tests: `test_<module_name>.py` or `test_<feature>.py`
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
* **Routers**: Contain API endpoint definitions.
|
||||
* **Schemas**: Define data structures using Pydantic models for request and response validation and serialization.
|
||||
* **Models**: Represent database entities (if using an ORM).
|
||||
* **Services**: Implement business logic, interacting with the database or other services.
|
||||
* **Dependencies**: Define dependency injection functions used in route handlers.
|
||||
* **Constants**: Store module-specific constants and error codes.
|
||||
* **Configuration**: Store module-specific environment variables and settings.
|
||||
* **Exceptions**: Define custom exceptions for specific modules.
|
||||
* **Utils**: Contains general-purpose utility functions.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
* **Layered Architecture:** Separate the application into distinct layers (e.g., presentation, business logic, data access). This improves maintainability and testability.
|
||||
* **Loose Coupling:** Design components to be independent and minimize dependencies between them. This allows for easier modification and replacement of components.
|
||||
* **High Cohesion:** Ensure that each component has a single, well-defined responsibility.
|
||||
* **Dependency Injection:** Use FastAPI's built-in dependency injection system to manage dependencies between components. This promotes testability and reusability. Favor interface-based dependency injection for added flexibility.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
* **Feature-Based Splitting:** Divide the codebase into modules based on application features (e.g., user management, product catalog, order processing). This makes it easier to understand and maintain the code.
|
||||
* **Vertical Slicing:** Group related components (e.g., routers, schemas, models, services) into slices that represent specific use cases or functionalities.
|
||||
* **Horizontal Splitting:** Separate components based on technical layers (e.g., presentation, business logic, data access). This is useful for enforcing separation of concerns but can lead to more complex dependencies if not managed carefully.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
Employ established design patterns and avoid common anti-patterns to write clean, efficient, and maintainable FastAPI code.
|
||||
|
||||
### 2.1 Design Patterns Specific to FastAPI
|
||||
|
||||
* **Repository Pattern:** Abstract data access logic behind a repository interface. This allows you to switch data sources easily (e.g., from a database to a mock for testing) and centralizes data access concerns.
|
||||
* **Service Layer Pattern:** Encapsulate business logic in service classes. Routers then call the service layer. Promotes testability and keeps routes thin and focused on request/response handling.
|
||||
* **Dependency Injection:** Utilize FastAPI's dependency injection system extensively for request validation, authentication, authorization, and accessing shared resources like database connections.
|
||||
* **Asynchronous Operations:** Favor `async` functions for I/O-bound tasks to improve performance and concurrency.
|
||||
* **Pydantic Models for Validation:** Use Pydantic models for request and response data validation. Enforce data types, constraints, and custom validation logic.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Configuration Management:** Use Pydantic's `BaseSettings` to manage environment variables and application settings.
|
||||
* **Database Interactions:** Use an ORM like SQLAlchemy for interacting with databases. Define database models and use them for data access.
|
||||
* **Authentication and Authorization:** Implement authentication and authorization using strategies like JWT (JSON Web Tokens) or OAuth 2.0. Use FastAPI's security utilities.
|
||||
* **Error Handling:** Use `HTTPException` for returning meaningful error responses to the client. Define custom exception classes for specific error conditions.
|
||||
* **Logging:** Configure logging using Python's `logging` module. Log important events and errors for debugging and monitoring.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Fat Route Handlers:** Avoid putting too much logic directly inside route handlers. Delegate complex tasks to service classes or utility functions.
|
||||
* **Tight Coupling:** Minimize dependencies between components to improve maintainability and testability.
|
||||
* **Ignoring Asynchronous Operations:** Blocking I/O in async routes can negate the benefits of concurrency. Ensure all I/O operations in async routes are non-blocking.
|
||||
* **Lack of Data Validation:** Failing to validate input data can lead to security vulnerabilities and unexpected behavior. Always use Pydantic models for data validation.
|
||||
* **Hardcoding Values:** Avoid hardcoding values in the code. Use configuration files or environment variables instead.
|
||||
* **Returning Pydantic objects directly from routes.** FastAPI makes an extra conversion. Return a dict.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
* **Stateless Applications:** FastAPI applications are typically stateless, meaning they don't store any persistent data within the application itself. This makes them easier to scale and deploy.
|
||||
* **External Data Stores:** Store application state in external data stores like databases, caches, or message queues.
|
||||
* **Dependency Injection for State:** Use dependency injection to provide access to shared resources or stateful objects to route handlers.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **Centralized Exception Handling:** Implement a global exception handler to catch unhandled exceptions and return appropriate error responses.
|
||||
* **Custom Exception Classes:** Define custom exception classes for specific error conditions. This makes it easier to identify and handle different types of errors.
|
||||
* **Logging Errors:** Log all errors for debugging and monitoring.
|
||||
* **Meaningful Error Messages:** Return meaningful error messages to the client to help them understand what went wrong.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
FastAPI is known for its performance, but optimizations are still crucial for high-load applications.
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Asynchronous Operations:** Utilize `async` and `await` for I/O-bound operations to prevent blocking the event loop.
|
||||
* **Database Connection Pooling:** Use a database connection pool to reuse database connections and reduce connection overhead.
|
||||
* **Caching:** Implement caching for frequently accessed data to reduce database load and improve response times. Use tools like Redis or Memcached.
|
||||
* **Gzip Compression:** Enable gzip compression for API responses to reduce the size of the data transmitted over the network.
|
||||
* **Load Balancing:** Distribute traffic across multiple instances of the application to improve scalability and availability.
|
||||
* **Profiling:** Use profiling tools to identify performance bottlenecks in the code.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Resource Management:** Properly manage resources like database connections, file handles, and network sockets. Close resources when they are no longer needed.
|
||||
* **Data Structures:** Use efficient data structures like sets and dictionaries for fast lookups.
|
||||
* **Generators:** Use generators for processing large datasets to avoid loading the entire dataset into memory at once.
|
||||
* **Object Reuse:** Reuse objects whenever possible to reduce memory allocation overhead. Consider using object pools for frequently used objects.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
* **Template Caching:** Enable template caching for Jinja2 templates to reduce rendering overhead.
|
||||
* **Minimize Template Logic:** Keep template logic simple and avoid complex computations in templates.
|
||||
* **Content Delivery Network (CDN):** Use a CDN to serve static assets like images, CSS, and JavaScript files.
|
||||
|
||||
### 3.4 Bundle Size Optimization (for Frontend Integration)
|
||||
|
||||
* **Code Splitting:** Split the frontend code into smaller bundles that can be loaded on demand.
|
||||
* **Tree Shaking:** Remove unused code from the frontend bundles using tree shaking techniques.
|
||||
* **Minification:** Minify the frontend code to reduce its size.
|
||||
* **Image Optimization:** Optimize images for the web by compressing them and using appropriate image formats.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
* **Lazy Loading of Modules:** Use lazy loading to load modules only when they are needed.
|
||||
* **Lazy Loading of Data:** Load data on demand instead of loading it all at once.
|
||||
* **Asynchronous Loading:** Use asynchronous loading to load data in the background without blocking the main thread.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
Security is paramount. Protect your FastAPI application from common web vulnerabilities.
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM with proper escaping.
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user input and escaping output data.
|
||||
* **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens.
|
||||
* **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms to protect sensitive data and resources.
|
||||
* **Insecure Direct Object References (IDOR):** Prevent IDOR by verifying that users have access to the objects they are requesting.
|
||||
* **Denial of Service (DoS):** Prevent DoS attacks by implementing rate limiting and input validation.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Pydantic Models:** Use Pydantic models to define data types, constraints, and validation rules for request bodies and query parameters.
|
||||
* **Custom Validation Logic:** Implement custom validation logic for complex validation scenarios.
|
||||
* **Sanitization:** Sanitize user input to remove potentially harmful characters or code.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **JWT (JSON Web Tokens):** Use JWT for stateless authentication. Generate a JWT when a user logs in and verify the JWT on subsequent requests.
|
||||
* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. Allow users to grant third-party applications access to their data without sharing their credentials.
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
|
||||
* **Attribute-Based Access Control (ABAC):** Implement ABAC to control access to resources based on user attributes and resource attributes.
|
||||
* **CORS (Cross-Origin Resource Sharing):** Configure CORS middleware properly to allow requests only from trusted origins.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
* **Hashing:** Hash passwords and other sensitive data using a strong hashing algorithm like bcrypt or Argon2.
|
||||
* **Data Masking:** Mask sensitive data in logs and other output.
|
||||
* **Data Anonymization:** Anonymize data to protect user privacy.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Always use HTTPS to encrypt communication between the client and the server.
|
||||
* **TLS/SSL Certificates:** Use valid TLS/SSL certificates to establish secure connections.
|
||||
* **Strict Transport Security (HSTS):** Enable HSTS to force browsers to use HTTPS for all requests to the application.
|
||||
* **Content Security Policy (CSP):** Configure CSP to prevent XSS attacks by controlling the sources from which the browser is allowed to load resources.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
Write comprehensive tests to ensure the quality and reliability of your FastAPI application.
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Test Individual Components:** Write unit tests to test individual components like functions, classes, and modules in isolation.
|
||||
* **Mock Dependencies:** Use mocking frameworks like `unittest.mock` or `pytest-mock` to mock external dependencies and isolate the component being tested.
|
||||
* **Test Edge Cases:** Test edge cases and boundary conditions to ensure that the component handles unexpected input correctly.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Test Interactions Between Components:** Write integration tests to test the interactions between different components of the application.
|
||||
* **Use a Test Database:** Use a separate test database for integration tests to avoid affecting the production database.
|
||||
* **Test API Endpoints:** Write integration tests to test the API endpoints of the application.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Test the Entire Application Flow:** Write end-to-end tests to test the entire application flow, from the client to the database.
|
||||
* **Use a Testing Framework:** Use a testing framework like Selenium or Cypress to automate end-to-end tests.
|
||||
* **Test User Interface (UI):** Test the user interface of the application to ensure that it is working correctly.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Organize Tests by Module:** Organize tests into separate directories or files based on the module or component being tested.
|
||||
* **Use Descriptive Test Names:** Use descriptive test names that clearly indicate what the test is verifying.
|
||||
* **Follow a Consistent Naming Convention:** Follow a consistent naming convention for test files and test functions.
|
||||
* **Keep Tests Concise:** Keep tests concise and focused on a single aspect of the component being tested.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Use Mocking Frameworks:** Use mocking frameworks like `unittest.mock` or `pytest-mock` to create mock objects and stub out external dependencies.
|
||||
* **Mock External APIs:** Mock external APIs to isolate the component being tested and avoid making actual API calls during testing.
|
||||
* **Stub Database Interactions:** Stub database interactions to avoid affecting the database during testing.
|
||||
* **Verify Interactions:** Verify that the component being tested interacts with the mock objects as expected.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
Be aware of common pitfalls and gotchas that can arise when developing FastAPI applications.
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
* **Incorrectly Using `Depends`:** Ensure `Depends` is used properly to inject dependencies into route handlers.
|
||||
* **Blocking I/O in Async Routes:** Avoid blocking I/O operations in async routes.
|
||||
* **Not Handling Exceptions:** Implement proper exception handling to prevent unhandled exceptions from crashing the application.
|
||||
* **Ignoring Security Best Practices:** Follow security best practices to protect the application from vulnerabilities.
|
||||
* **Not Writing Tests:** Write comprehensive tests to ensure the quality and reliability of the application.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
* **Unicode Handling:** Be aware of unicode handling issues when processing user input.
|
||||
* **Time Zones:** Handle time zones correctly when working with dates and times.
|
||||
* **Large File Uploads:** Handle large file uploads efficiently to prevent memory exhaustion.
|
||||
* **Concurrency Issues:** Be aware of concurrency issues when working with shared resources in a multi-threaded or multi-process environment.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
* **Check Changelogs:** Review the changelogs for FastAPI and its dependencies to be aware of any breaking changes or new features.
|
||||
* **Test Compatibility:** Test the application with different versions of FastAPI and its dependencies to ensure compatibility.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
* **Python Version:** Ensure that the application is compatible with the target Python version.
|
||||
* **Operating System:** Test the application on different operating systems to ensure compatibility.
|
||||
* **Database Compatibility:** Ensure that the application is compatible with the target database.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
* **Use a Debugger:** Use a debugger like `pdb` or `ipdb` to step through the code and inspect variables.
|
||||
* **Logging:** Use logging to track the execution flow and identify errors.
|
||||
* **Profiling:** Use profiling tools to identify performance bottlenecks.
|
||||
* **Remote Debugging:** Use remote debugging to debug applications running on remote servers.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
Utilize the right tools and environment for efficient FastAPI development.
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **IDE:** VS Code, PyCharm, or other IDE with Python support.
|
||||
* **Virtual Environment Manager:** `venv`, `conda`, or `poetry` for managing project dependencies.
|
||||
* **Package Manager:** `pip` or `poetry` for installing and managing Python packages.
|
||||
* **Debugger:** `pdb` or `ipdb` for debugging Python code.
|
||||
* **Profiler:** `cProfile` or `py-spy` for profiling Python code.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **`requirements.txt`:** Use `requirements.txt` to specify project dependencies. Generate it using `pip freeze > requirements.txt`.
|
||||
* **`pyproject.toml`:** Consider using `pyproject.toml` (with Poetry or similar tools) for more advanced dependency management and build configuration.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **Linters:** Use linters like `flake8`, `pylint`, or `ruff` to enforce code style and identify potential errors.
|
||||
* **Formatters:** Use code formatters like `black` or `autopep8` to automatically format the code according to PEP 8 standards.
|
||||
* **Pre-commit Hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **Containerization:** Use Docker to containerize the application for easy deployment and scaling.
|
||||
* **Reverse Proxy:** Use a reverse proxy like Nginx or Apache to handle incoming requests and forward them to the application.
|
||||
* **Process Manager:** Use a process manager like Supervisor or systemd to manage the application process.
|
||||
* **Load Balancing:** Use a load balancer to distribute traffic across multiple instances of the application.
|
||||
* **Monitoring:** Monitor the application using tools like Prometheus or Grafana.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Continuous Integration (CI):** Set up a CI pipeline to automatically build, test, and lint the code on every commit.
|
||||
* **Continuous Delivery (CD):** Set up a CD pipeline to automatically deploy the application to the production environment after the CI pipeline has passed.
|
||||
* **Version Control:** Use a version control system like Git to manage the code and track changes.
|
||||
* **Automated Testing:** Integrate automated tests into the CI/CD pipeline to ensure that the application is working correctly before deployment.
|
||||
* **Automated Rollbacks:** Implement automated rollbacks to revert to a previous version of the application if a deployment fails.
|
||||
|
||||
## Conclusion
|
||||
|
||||
By adhering to these best practices, you can develop robust, scalable, and maintainable FastAPI applications that are secure, performant, and easy to test. This guide provides a foundation for building high-quality APIs with FastAPI.
|
||||
@@ -0,0 +1,199 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing Flask applications, covering code structure, security, performance, and testing.
|
||||
globs: **/*.py
|
||||
---
|
||||
- ## Code Organization and Structure:
|
||||
- **Directory Structure Best Practices:**
|
||||
- Follow a modular and organized project structure. A common structure is:
|
||||
|
||||
project_root/
|
||||
├── app/
|
||||
│ ├── __init__.py
|
||||
│ ├── models.py
|
||||
│ ├── views.py # Or controllers.py
|
||||
│ ├── forms.py
|
||||
│ ├── utils.py # Helper functions
|
||||
│ ├── api/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── routes.py
|
||||
│ ├── templates/
|
||||
│ │ └── ...
|
||||
│ ├── static/
|
||||
│ │ └── ...
|
||||
├── tests/
|
||||
│ ├── __init__.py
|
||||
│ ├── conftest.py # Fixtures for tests
|
||||
│ ├── test_models.py
|
||||
│ ├── test_views.py
|
||||
├── migrations/
|
||||
│ └── ... # Alembic migrations
|
||||
├── venv/ # Virtual environment
|
||||
├── .env # Environment variables (use with caution, not for sensitive data in production)
|
||||
├── config.py # Application configuration
|
||||
├── requirements.txt or pyproject.toml # Dependencies
|
||||
├── run.py # Application entry point
|
||||
|
||||
- Use Blueprints to organize routes and views into logical modules. Blueprints promote reusability and maintainability.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent file names.
|
||||
- Examples: `models.py`, `views.py`, `forms.py`, `utils.py`, `routes.py`, `test_*.py`.
|
||||
- Maintain consistency throughout the project.
|
||||
- **Module Organization:**
|
||||
- Group related functionality into modules. For instance, database models in `models.py`, user authentication logic in `auth.py`, and utility functions in `utils.py`.
|
||||
- Use `__init__.py` files to make directories packages, allowing you to import modules within the directory using relative paths.
|
||||
- **Component Architecture:**
|
||||
- Design components with clear responsibilities and interfaces.
|
||||
- Consider using a layered architecture (e.g., presentation, business logic, data access) to separate concerns.
|
||||
- Use dependency injection to decouple components.
|
||||
- **Code Splitting Strategies:**
|
||||
- Decompose large modules into smaller, more manageable files.
|
||||
- Extract reusable code into separate modules or packages.
|
||||
- Employ lazy loading for modules that are not immediately needed.
|
||||
|
||||
- ## Common Patterns and Anti-patterns:
|
||||
- **Design Patterns Specific to Flask:**
|
||||
- **Application Factory:** Use the application factory pattern to create Flask application instances. This allows for different configurations for different environments (development, testing, production).
|
||||
python
|
||||
def create_app(config_name):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_name])
|
||||
config[config_name].init_app(app)
|
||||
|
||||
# Initialize extensions (e.g., db, mail) here
|
||||
db.init_app(app)
|
||||
mail.init_app(app)
|
||||
|
||||
# Register blueprints
|
||||
from .main import main as main_blueprint
|
||||
app.register_blueprint(main_blueprint)
|
||||
|
||||
return app
|
||||
|
||||
- **Blueprints:** Organize application functionality into reusable blueprints.
|
||||
python
|
||||
from flask import Blueprint
|
||||
|
||||
bp = Blueprint('my_blueprint', __name__, url_prefix='/my_blueprint')
|
||||
|
||||
@bp.route('/route')
|
||||
def my_route():
|
||||
return 'Hello from my_blueprint'
|
||||
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Database Interactions:** Use Flask-SQLAlchemy or another ORM for database interactions. Define models to represent database tables.
|
||||
- **Form Handling:** Use Flask-WTF for form handling. This provides CSRF protection and simplifies form validation.
|
||||
- **Authentication:** Use Flask-Login for user authentication. It provides utilities for managing user sessions and protecting routes.
|
||||
- **API Development:** Use Flask-RESTful or Flask-API for building RESTful APIs. Consider using Marshmallow for serializing and deserializing data.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Global State:** Avoid using global variables to store application state. Use the `g` object or session variables instead.
|
||||
- **Tight Coupling:** Design components with loose coupling to improve maintainability and testability.
|
||||
- **Fat Models/Views:** Keep models and views focused on their primary responsibilities. Move complex business logic to separate modules.
|
||||
- **Hardcoding Configuration:** Avoid hardcoding configuration values. Use environment variables or a configuration file.
|
||||
- **State Management Best Practices:**
|
||||
- Use the Flask `session` object to store user-specific data across requests.
|
||||
- For application-wide state, consider using a database or a caching mechanism.
|
||||
- Avoid storing sensitive data in the session without proper encryption.
|
||||
- **Error Handling Patterns:**
|
||||
- Use `try...except` blocks to handle exceptions gracefully.
|
||||
- Implement custom error handlers for specific exceptions. Return appropriate HTTP status codes and error messages.
|
||||
- Use logging to record errors and warnings.
|
||||
- Use Flask's `abort()` function to raise HTTP exceptions.
|
||||
|
||||
- ## Performance Considerations:
|
||||
- **Optimization Techniques:**
|
||||
- **Caching:** Implement caching to reduce database queries and improve response times. Use Flask-Caching or Redis.
|
||||
- **Database Optimization:** Optimize database queries and use indexes to improve performance.
|
||||
- **Profiling:** Use a profiler to identify performance bottlenecks in your code.
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly closing database connections and releasing resources.
|
||||
- Use generators to process large datasets efficiently.
|
||||
- **Rendering Optimization:**
|
||||
- Minimize the number of database queries in templates.
|
||||
- Use template caching to reduce rendering time.
|
||||
- **Bundle Size Optimization:**
|
||||
- For larger front-end applications, use a bundler like Webpack or Parcel to optimize JavaScript and CSS files. Minify and compress assets.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Implement lazy loading for images and other assets to improve initial page load time.
|
||||
- Use code splitting to load only the necessary JavaScript code for each page.
|
||||
|
||||
- ## Security Best Practices:
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates. Use Jinja2's autoescaping feature.
|
||||
- **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM.
|
||||
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using Flask-WTF, which provides CSRF protection.
|
||||
- **Authentication and Authorization Issues:** Implement secure authentication and authorization mechanisms. Use strong passwords and protect user credentials.
|
||||
- **Input Validation:**
|
||||
- Validate all user input to prevent malicious data from entering your application.
|
||||
- Use Flask-WTF for form validation.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use Flask-Login for user authentication.
|
||||
- Implement role-based access control (RBAC) to restrict access to certain resources.
|
||||
- Use JWT (JSON Web Tokens) for API authentication.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and the server.
|
||||
- Store passwords securely using a strong hashing algorithm (e.g., bcrypt).
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement authentication and authorization for API endpoints.
|
||||
- Validate API requests and responses.
|
||||
- Use rate limiting to prevent abuse.
|
||||
|
||||
- ## Testing Approaches:
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests to verify the functionality of individual components.
|
||||
- Use pytest or unittest for writing and running tests.
|
||||
- Mock external dependencies to isolate components during testing.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between different components.
|
||||
- Test the integration between the application and the database.
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to simulate user interactions with the application.
|
||||
- Use Selenium or Cypress for end-to-end testing.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on functionality.
|
||||
- Use descriptive test names.
|
||||
- Follow the Arrange-Act-Assert pattern in your tests.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate components during testing.
|
||||
- Use the `unittest.mock` module or a third-party mocking library like `mock`.
|
||||
|
||||
- ## Common Pitfalls and Gotchas:
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Not using a virtual environment:** Always use a virtual environment to isolate project dependencies.
|
||||
- **Not handling exceptions properly:** Handle exceptions gracefully to prevent application crashes.
|
||||
- **Exposing sensitive data:** Avoid exposing sensitive data in logs or error messages.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Handling Unicode correctly:** Be aware of Unicode encoding issues when working with text data.
|
||||
- **Dealing with time zones:** Use a consistent time zone throughout the application.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility issues when upgrading Flask or its dependencies.
|
||||
- Consult the Flask documentation for version-specific information.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your application is compatible with different browsers and operating systems.
|
||||
- Test your application on different devices.
|
||||
- **Debugging Strategies:**
|
||||
- Use the Flask debugger to identify and fix errors.
|
||||
- Use logging to record errors and warnings.
|
||||
- Use a profiler to identify performance bottlenecks.
|
||||
|
||||
- ## Tooling and Environment:
|
||||
- **Recommended Development Tools:**
|
||||
- **Virtual Environment Manager:** `virtualenv`, `venv`, or `conda`
|
||||
- **Package Manager:** `pip` or `pipenv` or `poetry`
|
||||
- **IDE/Text Editor:** VS Code, PyCharm, Sublime Text
|
||||
- **Debugger:** `pdb` or `ipdb`
|
||||
- **Profiler:** `cProfile`
|
||||
- **Build Configuration:**
|
||||
- Use a `requirements.txt` or `pyproject.toml` file to specify project dependencies.
|
||||
- Use a build system like `setuptools` or `poetry` to package your application.
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter like `flake8` or `pylint` to enforce code style guidelines.
|
||||
- Use a formatter like `black` or `autopep8` to automatically format your code.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a production-ready WSGI server like Gunicorn or uWSGI.
|
||||
- Use a reverse proxy like Nginx or Apache to serve static files and handle SSL termination.
|
||||
- Deploy your application to a cloud platform like AWS, Google Cloud, or Azure.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD pipeline to automate testing, building, and deployment.
|
||||
- Use tools like Jenkins, Travis CI, or GitHub Actions.
|
||||
@@ -0,0 +1,318 @@
|
||||
---
|
||||
description: Comprehensive best practices for developing robust, efficient, and maintainable applications using the actix-web framework in Rust. This rule covers coding standards, project structure, performance, security, testing, and common pitfalls.
|
||||
globs: **/*.rs
|
||||
---
|
||||
# Actix-web Best Practices: A Comprehensive Guide
|
||||
|
||||
This guide provides a comprehensive overview of best practices for developing applications using the actix-web framework in Rust. It covers various aspects of development, including code organization, performance optimization, security, testing, and common pitfalls.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
A well-organized codebase is crucial for maintainability and scalability. Here's how to structure your actix-web project effectively:
|
||||
|
||||
### 1.1. Directory Structure Best Practices
|
||||
|
||||
Adopt a modular and layered architecture. A common and recommended directory structure is as follows:
|
||||
|
||||
|
||||
project_root/
|
||||
├── src/
|
||||
│ ├── main.rs # Entry point of the application
|
||||
│ ├── lib.rs # Library file if extracting common functionality
|
||||
│ ├── modules/
|
||||
│ │ ├── mod.rs # Module declaration
|
||||
│ │ ├── auth/ # Authentication module
|
||||
│ │ │ ├── mod.rs # Auth module declaration
|
||||
│ │ │ ├── models.rs # Auth models
|
||||
│ │ │ ├── routes.rs # Auth routes
|
||||
│ │ │ ├── handlers.rs # Auth handlers
|
||||
│ │ ├── users/ # User management module
|
||||
│ │ │ ├── mod.rs # User module declaration
|
||||
│ │ │ ├── models.rs # User models
|
||||
│ │ │ ├── routes.rs # User routes
|
||||
│ │ │ ├── handlers.rs # User handlers
|
||||
│ ├── models/ # Data models
|
||||
│ │ ├── mod.rs
|
||||
│ │ ├── user.rs # User model
|
||||
│ │ ├── post.rs # Post model
|
||||
│ ├── routes/ # Route configurations
|
||||
│ │ ├── mod.rs
|
||||
│ │ ├── auth_routes.rs # Authentication routes
|
||||
│ │ ├── user_routes.rs # User routes
|
||||
│ ├── handlers/ # Request handlers (controllers)
|
||||
│ │ ├── mod.rs
|
||||
│ │ ├── auth_handlers.rs # Authentication handlers
|
||||
│ │ ├── user_handlers.rs # User handlers
|
||||
│ ├── middleware/ # Custom middleware components
|
||||
│ │ ├── mod.rs
|
||||
│ │ ├── logger.rs # Logging middleware
|
||||
│ │ ├── auth.rs # Authentication middleware
|
||||
│ ├── utils/ # Utility functions and modules
|
||||
│ │ ├── mod.rs
|
||||
│ │ ├── db.rs # Database connection utility
|
||||
│ ├── errors/ # Custom error definitions
|
||||
│ │ ├── mod.rs
|
||||
│ │ ├── app_error.rs # Application-specific error types
|
||||
├── tests/ # Integration and unit tests
|
||||
│ ├── mod.rs
|
||||
│ ├── api_tests.rs # Integration tests for API endpoints
|
||||
├── .env # Environment variables
|
||||
├── Cargo.toml # Project dependencies and metadata
|
||||
├── Cargo.lock # Dependency lockfile
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **Modules:** Use lowercase, descriptive names (e.g., `auth`, `users`, `posts`).
|
||||
* **Files:** Use lowercase with underscores (e.g., `user_routes.rs`, `auth_handlers.rs`).
|
||||
* **Models:** Use singular nouns (e.g., `user.rs`, `post.rs`).
|
||||
* **Handlers:** Use descriptive names indicating the action performed (e.g., `create_user`, `get_user`).
|
||||
* **Routes:** Use names indicating the resource they handle (e.g., `user_routes`, `auth_routes`).
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
* **Explicit Module Declarations:** Always declare submodules in `mod.rs` files. This ensures proper module resolution and prevents naming conflicts.
|
||||
* **Clear Boundaries:** Each module should have a well-defined responsibility. Avoid mixing unrelated functionalities within the same module.
|
||||
* **Public vs. Private:** Use `pub` keyword judiciously to control visibility. Keep implementation details private to modules to prevent accidental external dependencies.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* **Layered Architecture:** Separate concerns into distinct layers (e.g., data access, business logic, presentation). This improves testability and maintainability.
|
||||
* **Dependency Injection:** Use dependency injection to provide dependencies to handlers. This makes it easier to test and configure your application.
|
||||
* **Services:** Encapsulate business logic into services. Handlers should primarily focus on request/response handling and delegate business logic to services.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* **Feature-Based Splitting:** Group code based on features (e.g., authentication, user management). This makes it easier to understand and maintain related code.
|
||||
* **Module-Based Splitting:** Split code into modules based on functionality. This improves code organization and reusability.
|
||||
* **Lazy Loading (Future Enhancement):** For very large applications, consider lazy loading modules or features to reduce initial startup time. This can be accomplished by dynamically enabling parts of your application based on configuration or runtime conditions.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns Specific to Actix-web
|
||||
|
||||
* **Extractor Pattern:** Use extractors to handle different types of incoming data (e.g., `Path`, `Query`, `Json`, `Form`). Extractors simplify handler logic and provide type safety.
|
||||
* **Middleware Pattern:** Implement custom middleware for tasks like logging, authentication, and request modification. Middleware allows you to intercept and process requests before they reach the handlers.
|
||||
* **State Management Pattern:** Use `web::Data` to share application state across handlers. This provides a thread-safe way to access shared resources like database connections and configuration settings.
|
||||
* **Error Handling Pattern:** Define custom error types and implement the `ResponseError` trait for centralized error handling and consistent error responses.
|
||||
|
||||
### 2.2. Recommended Approaches for Common Tasks
|
||||
|
||||
* **Database Integration:** Use an asynchronous database driver like `tokio-postgres` or `sqlx` for efficient database interactions.
|
||||
* **Authentication:** Implement authentication using JWT (JSON Web Tokens) or other secure authentication mechanisms.
|
||||
* **Authorization:** Implement role-based access control (RBAC) or attribute-based access control (ABAC) to restrict access to resources based on user roles or attributes.
|
||||
* **Logging:** Use a logging framework like `tracing` or `log` for structured logging and monitoring.
|
||||
* **Configuration Management:** Use a configuration library like `config` or `dotenv` to manage application settings from environment variables and configuration files.
|
||||
|
||||
### 2.3. Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Long Handler Functions:** Keep handler functions short and focused. Delegate complex logic to services or helper functions.
|
||||
* **Tight Coupling:** Avoid tight coupling between modules. Use interfaces and dependency injection to decouple components.
|
||||
* **Ignoring Errors:** Always handle errors gracefully and provide informative error messages to the client.
|
||||
* **Blocking Operations in Handlers:** Avoid performing blocking operations (e.g., synchronous I/O) in handler functions. Use asynchronous operations to prevent blocking the event loop.
|
||||
* **Overusing Global State:** Minimize the use of global state. Prefer passing state as dependencies to handler functions.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Immutable State:** Prefer immutable state whenever possible. This reduces the risk of race conditions and makes it easier to reason about the application.
|
||||
* **Thread-Safe Data Structures:** Use thread-safe data structures like `Arc<Mutex<T>>` or `RwLock<T>` to share mutable state across threads.
|
||||
* **Avoid Direct Mutability:** Avoid directly mutating shared state. Instead, use atomic operations or message passing to coordinate state updates.
|
||||
* **Dependency Injection:** Use dependency injection to provide state to handler functions. This makes it easier to test and configure the application.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **Custom Error Types:** Define custom error types to represent different error scenarios in your application.
|
||||
* **`ResponseError` Trait:** Implement the `ResponseError` trait for custom error types to generate appropriate HTTP responses.
|
||||
* **Centralized Error Handling:** Use a centralized error handling mechanism (e.g., middleware) to catch and process errors consistently.
|
||||
* **Informative Error Messages:** Provide informative error messages to the client to help them understand and resolve the issue.
|
||||
* **Logging Errors:** Log errors with sufficient detail to help diagnose and debug issues.
|
||||
* **`Result` Type:** Leverage the `Result` type effectively, propagating errors up the call stack using the `?` operator, and handle them at the appropriate level.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
Optimizing performance is crucial for building scalable and responsive actix-web applications.
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Asynchronous Operations:** Use asynchronous operations for I/O-bound tasks (e.g., database access, network requests) to prevent blocking the event loop.
|
||||
* **Connection Pooling:** Use connection pooling for database connections to reduce the overhead of establishing new connections.
|
||||
* **Caching:** Implement caching for frequently accessed data to reduce database load and improve response times.
|
||||
* **Compression:** Enable compression (e.g., gzip) for responses to reduce the amount of data transmitted over the network.
|
||||
* **Keep-Alive Connections:** Use keep-alive connections to reuse existing TCP connections and reduce connection establishment overhead.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Avoid Unnecessary Cloning:** Minimize cloning of data to reduce memory allocations and copying.
|
||||
* **Use References:** Use references instead of copying data whenever possible.
|
||||
* **Smart Pointers:** Use smart pointers (e.g., `Box`, `Arc`, `Rc`) to manage memory efficiently.
|
||||
* **String Handling:** Be mindful of string handling. Use `String` when ownership is needed, and `&str` when a read-only view is sufficient.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
* **Template Caching:** Cache templates to reduce the overhead of parsing and compiling templates on each request.
|
||||
* **Minimize DOM Updates:** Minimize DOM updates in the client-side JavaScript code to improve rendering performance.
|
||||
* **Efficient Serialization:** Ensure your data serialization is efficient, using appropriate data structures and serialization libraries (e.g., `serde_json`).
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
|
||||
* **Dependency Pruning:** Remove unused dependencies from your `Cargo.toml` file to reduce the bundle size.
|
||||
* **Feature Flags:** Use feature flags to enable or disable optional features at compile time.
|
||||
* **Code Minification:** Use code minification to reduce the size of your JavaScript and CSS files.
|
||||
|
||||
### 3.5. Lazy Loading Strategies
|
||||
|
||||
* **Lazy Initialization:** Use lazy initialization for expensive resources to defer their creation until they are actually needed.
|
||||
* **On-Demand Loading:** Load resources on demand (e.g., images, data) to reduce the initial load time.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
Security is paramount for building robust and reliable actix-web applications.
|
||||
|
||||
### 4.1. Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks.
|
||||
* **Cross-Site Scripting (XSS):** Sanitize user input and escape output to prevent XSS attacks.
|
||||
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent unauthorized requests from other websites.
|
||||
* **Authentication and Authorization:** Use strong authentication and authorization mechanisms to protect sensitive resources.
|
||||
* **Denial-of-Service (DoS):** Implement rate limiting and other defense mechanisms to prevent DoS attacks.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Validate All Input:** Validate all user input to ensure that it conforms to the expected format and range.
|
||||
* **Use Type Safety:** Use type safety to prevent invalid data from being processed.
|
||||
* **Regular Expressions:** Use regular expressions to validate complex input patterns.
|
||||
* **Whitelist vs. Blacklist:** Prefer whitelisting valid input over blacklisting invalid input.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* **JWT (JSON Web Tokens):** Use JWT for stateless authentication and authorization.
|
||||
* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
|
||||
* **RBAC (Role-Based Access Control):** Use RBAC to restrict access to resources based on user roles.
|
||||
* **ABAC (Attribute-Based Access Control):** Use ABAC to restrict access to resources based on user attributes.
|
||||
* **Password Hashing:** Always hash passwords using a strong hashing algorithm (e.g., bcrypt, Argon2) and store them securely.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
* **Data Masking:** Mask sensitive data to prevent unauthorized access.
|
||||
* **Data Anonymization:** Anonymize data to protect user privacy.
|
||||
* **Access Control:** Implement strict access control policies to restrict access to sensitive data.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for all API communication to encrypt data in transit.
|
||||
* **TLS Certificates:** Use valid TLS certificates from a trusted certificate authority.
|
||||
* **API Keys:** Use API keys to authenticate API clients.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent abuse and DoS attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
Thorough testing is essential for ensuring the quality and reliability of actix-web applications.
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* **Test Individual Modules:** Unit test individual modules and functions in isolation.
|
||||
* **Mock Dependencies:** Use mocking to isolate units from external dependencies (e.g., database, API).
|
||||
* **Test Edge Cases:** Test edge cases and boundary conditions to ensure that the code handles them correctly.
|
||||
* **Table-Driven Tests:** Use table-driven tests to test multiple scenarios with different inputs and expected outputs.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Test API Endpoints:** Integration test API endpoints to ensure that they function correctly together.
|
||||
* **Test Database Interactions:** Test database interactions to ensure that data is read and written correctly.
|
||||
* **Test Middleware:** Test middleware to ensure that they correctly process requests and responses.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **Simulate User Interactions:** End-to-end tests simulate user interactions to test the entire application flow.
|
||||
* **Use a Testing Framework:** Use a testing framework (e.g., Selenium, Cypress) to automate end-to-end tests.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Test Directory:** Keep tests in a separate `tests` directory.
|
||||
* **Test Modules:** Organize tests into modules that mirror the application structure.
|
||||
* **Test Naming:** Use descriptive names for test functions to indicate what they are testing.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock External Dependencies:** Mock external dependencies (e.g., database, API) to isolate units from external factors.
|
||||
* **Use Mocking Libraries:** Use mocking libraries (e.g., `mockall`) to create mock objects and define their behavior.
|
||||
* **Stub Data:** Use stub data to simulate different scenarios and test edge cases.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
Be aware of common pitfalls and gotchas when developing actix-web applications.
|
||||
|
||||
### 6.1. Frequent Mistakes Developers Make
|
||||
|
||||
* **Blocking Operations:** Performing blocking operations in handler functions can block the event loop and degrade performance.
|
||||
* **Incorrect Error Handling:** Ignoring errors or not handling them correctly can lead to unexpected behavior and security vulnerabilities.
|
||||
* **Not Validating Input:** Not validating user input can lead to security vulnerabilities and data corruption.
|
||||
* **Overusing Global State:** Overusing global state can make the application difficult to reason about and test.
|
||||
* **Not Using Asynchronous Operations:** Not using asynchronous operations for I/O-bound tasks can degrade performance.
|
||||
|
||||
### 6.2. Edge Cases to be Aware Of
|
||||
|
||||
* **Handling Large Requests:** Be mindful of handling large requests and implement appropriate size limits to prevent DoS attacks.
|
||||
* **Handling Concurrent Requests:** Ensure that the application can handle concurrent requests efficiently and without race conditions.
|
||||
* **Handling Network Errors:** Handle network errors gracefully and provide informative error messages to the client.
|
||||
* **Handling Database Connection Errors:** Handle database connection errors gracefully and implement retry mechanisms.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Breaking Changes:** Be aware of breaking changes in actix-web and its dependencies.
|
||||
* **Deprecated Features:** Avoid using deprecated features and migrate to the recommended alternatives.
|
||||
* **Compatibility:** Ensure that the application is compatible with the target Rust version and operating system.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Rust Version:** Ensure compatibility with the supported Rust versions.
|
||||
* **Operating System:** Test on different operating systems (Linux, macOS, Windows).
|
||||
* **Browser Compatibility (if applicable):** If the application includes a front-end, test with various browsers.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **Logging:** Use logging to track the application's execution flow and identify potential issues.
|
||||
* **Debugging Tools:** Use debugging tools (e.g., `gdb`, `lldb`) to inspect the application's state and step through the code.
|
||||
* **Unit Tests:** Write unit tests to isolate and debug individual modules and functions.
|
||||
* **Profiling:** Use profiling tools to identify performance bottlenecks.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
Using the right tools and environment can significantly improve the development experience and productivity.
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **Rust IDE:** Use a Rust IDE (e.g., Visual Studio Code with the Rust extension, IntelliJ Rust) for code completion, syntax highlighting, and debugging.
|
||||
* **Cargo:** Use Cargo, the Rust package manager, for managing dependencies and building the application.
|
||||
* **Rustup:** Use Rustup for managing Rust toolchains and versions.
|
||||
* **Clippy:** Use Clippy, a Rust linter, for identifying potential code quality issues.
|
||||
* **Formatter:** Use rustfmt to automatically format the code according to the Rust style guide.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **Release Mode:** Build the application in release mode for optimized performance.
|
||||
* **Link-Time Optimization (LTO):** Enable link-time optimization to improve performance.
|
||||
* **Codegen Units:** Experiment with different codegen unit settings to optimize compilation time and code size.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **Clippy:** Use Clippy to identify potential code quality issues and enforce coding standards.
|
||||
* **Rustfmt:** Use rustfmt to automatically format the code according to the Rust style guide.
|
||||
* **Pre-commit Hooks:** Use pre-commit hooks to automatically run Clippy and rustfmt before committing changes.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies into a portable container.
|
||||
* **Orchestration:** Use container orchestration (e.g., Kubernetes) to manage and scale the application.
|
||||
* **Reverse Proxy:** Use a reverse proxy (e.g., Nginx, Apache) to handle incoming requests and route them to the application.
|
||||
* **Load Balancing:** Use load balancing to distribute traffic across multiple instances of the application.
|
||||
* **Monitoring:** Implement monitoring to track the application's health and performance.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **Continuous Integration (CI):** Use a CI system (e.g., GitHub Actions, GitLab CI, Jenkins) to automatically build, test, and lint the code on every commit.
|
||||
* **Continuous Delivery (CD):** Use a CD system to automatically deploy the application to production after it passes all tests.
|
||||
* **Automated Testing:** Automate unit, integration, and end-to-end tests in the CI/CD pipeline.
|
||||
|
||||
By following these best practices, you can build robust, efficient, and maintainable actix-web applications that meet the highest standards of quality and security. Remember to stay up-to-date with the latest recommendations and adapt them to your specific project needs.
|
||||
@@ -0,0 +1,113 @@
|
||||
---
|
||||
description: Comprehensive guidelines for developing robust and maintainable web applications with the Rocket web framework, covering code organization, security, performance, testing, and more.
|
||||
globs: **/*.rs
|
||||
---
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:** Organize your project with a clear and maintainable directory structure. A common pattern is:
|
||||
- `src/`: Contains the main source code.
|
||||
- `main.rs`: Entry point of the application.
|
||||
- `lib.rs`: Defines library components.
|
||||
- `routes/`: Contains route handlers.
|
||||
- `mod.rs`: Defines and exports route modules.
|
||||
- `resource_name.rs`: Individual route files.
|
||||
- `models/`: Defines data structures and database interactions.
|
||||
- `mod.rs`: Defines and exports model modules.
|
||||
- `data_model.rs`: Individual model definitions.
|
||||
- `utils/`: Utility functions and modules.
|
||||
- `mod.rs`: Defines and exports utility modules.
|
||||
- `helper_functions.rs`: Individual utility function files.
|
||||
- `config/`: Configuration files and settings.
|
||||
- `static/`: Static assets like CSS, JavaScript, and images.
|
||||
- `templates/`: Templates for rendering dynamic content (using templating engines like Handlebars or Tera).
|
||||
- `tests/`: Unit and integration tests.
|
||||
- `migrations/`: Database migrations (if applicable).
|
||||
- **File Naming Conventions:** Use descriptive and consistent file names. Follow Rust's conventions, such as `snake_case` for file and module names. For example, `user_routes.rs`, `database_connection.rs`.
|
||||
- **Module Organization:** Break down your code into logical modules. Use `mod.rs` files to define and re-export modules within a directory.
|
||||
- **Component Architecture:** Design your application using a component-based architecture. This promotes reusability and maintainability. Consider using traits to define interfaces between components.
|
||||
- **Code Splitting Strategies:** For larger applications, split your code into smaller, manageable crates to improve compilation times and code organization.
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Repository Pattern:** Abstract data access logic behind a repository interface.
|
||||
- **Service Layer Pattern:** Decouple route handlers from business logic using a service layer.
|
||||
- **State Pattern:** Manage complex state transitions within route handlers or components.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Database Interactions:** Use an ORM like Diesel or SeaORM to interact with databases. Use connection pooling to efficiently manage database connections.
|
||||
- **Authentication and Authorization:** Implement authentication using JWT (JSON Web Tokens) or sessions. Use role-based access control (RBAC) for authorization.
|
||||
- **Input Validation:** Thoroughly validate user input to prevent security vulnerabilities and data corruption.
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Global Variables:** Avoid using global variables, as they can lead to unexpected side effects and make code harder to reason about. Use dependency injection instead.
|
||||
- **Tight Coupling:** Minimize dependencies between components. Use interfaces and abstractions to decouple components.
|
||||
- **Long Functions:** Break down long functions into smaller, more manageable functions.
|
||||
- **State Management:** Use Rocket's managed state feature (`#[rocket::State]`) to manage application-level state.
|
||||
- **Error Handling:** Use Rust's `Result` type for error handling. Provide informative error messages to the user.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- **Asynchronous Programming:** Use asynchronous programming (`async/await`) to handle concurrent requests efficiently.
|
||||
- **Caching:** Implement caching to reduce database load and improve response times.
|
||||
- **Connection Pooling:** Use connection pooling to reuse database connections.
|
||||
- **Memory Management:** Be mindful of memory allocation and deallocation. Use Rust's ownership and borrowing system to prevent memory leaks and data races.
|
||||
- **Rendering Optimization:** Optimize your templates to reduce rendering time. Use template caching.
|
||||
- **Bundle Size Optimization:** Minimize the size of your application's binary. Use release mode compilation (`cargo build --release`). Strip debug symbols.
|
||||
- **Lazy Loading Strategies:** Load resources on demand to improve initial page load time.
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM.
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection using tokens.
|
||||
- **Input Validation:** Validate all user input on both the client-side and server-side.
|
||||
- **Authentication and Authorization:**
|
||||
- Use strong password hashing algorithms (e.g., bcrypt or Argon2).
|
||||
- Implement two-factor authentication (2FA).
|
||||
- Use role-based access control (RBAC) to restrict access to resources.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and server.
|
||||
- Store passwords securely using a strong hashing algorithm.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Use API keys or JWT for authentication.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:** Write unit tests to verify the functionality of individual functions and modules. Use the `#[cfg(test)]` attribute to define test modules.
|
||||
- **Integration Testing:** Write integration tests to verify the interaction between different parts of your application. Test routes and database interactions.
|
||||
- **End-to-End Testing:** Write end-to-end tests to verify the complete functionality of your application. Use a testing framework like Selenium or Cypress.
|
||||
- **Test Organization:** Organize your tests in a clear and maintainable way. Create separate test modules for each component or module.
|
||||
- **Mocking and Stubbing:** Use mocking and stubbing to isolate units of code during testing. Use a mocking framework like Mockall.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- **Forgetting to handle errors:** Always handle errors properly using `Result` and provide informative error messages.
|
||||
- **Not validating user input:** Always validate user input to prevent security vulnerabilities.
|
||||
- **Using global state:** Avoid using global state, as it can lead to unexpected side effects.
|
||||
- **Edge Cases:**
|
||||
- **Handling concurrent requests:** Use asynchronous programming to handle concurrent requests efficiently.
|
||||
- **Dealing with large files:** Use streaming to process large files without loading them into memory.
|
||||
- **Handling database connection errors:** Implement retry logic to handle database connection errors.
|
||||
- **Version-Specific Issues:** Be aware of version-specific issues and compatibility concerns. Consult the Rocket documentation and release notes.
|
||||
- **Compatibility Concerns:** Ensure that your application is compatible with the target platform and browser versions.
|
||||
- **Debugging Strategies:**
|
||||
- Use the `println!` macro for debugging.
|
||||
- Use a debugger like GDB or LLDB.
|
||||
- Use logging to track the execution of your application.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Development Tools:**
|
||||
- **Rust toolchain:** Install the Rust toolchain using `rustup`.
|
||||
- **IDE:** Use an IDE like Visual Studio Code with the Rust Analyzer extension.
|
||||
- **Database client:** Use a database client like DBeaver or pgAdmin.
|
||||
- **Build Configuration:** Configure your build using `Cargo.toml`. Specify dependencies, build scripts, and other build settings.
|
||||
- **Linting and Formatting:**
|
||||
- Use `rustfmt` for code formatting.
|
||||
- Use `clippy` for linting.
|
||||
- Configure your IDE to automatically format and lint your code.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a process manager like systemd or PM2 to manage your application.
|
||||
- Use a reverse proxy like Nginx or Apache to handle incoming requests.
|
||||
- Use a load balancer to distribute traffic across multiple instances of your application.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD platform like GitHub Actions or GitLab CI to automate your build, test, and deployment process.
|
||||
- Write tests to ensure that your application is working correctly before deploying.
|
||||
Reference in New Issue
Block a user